Skip to content

Instantly share code, notes, and snippets.

@sebkopf
Last active April 6, 2023 10:11
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save sebkopf/a8bf2033f3eda527fa61 to your computer and use it in GitHub Desktop.
Save sebkopf/a8bf2033f3eda527fa61 to your computer and use it in GitHub Desktop.
wolfram alpha from R

Wolfram Alpha API from R

The attached code file provides an easy basic interface to the Wolfram Alpha API. Inspired by the wolframalpha module available for Python.

source("wa_lib.R")

Initialize client

This requires an app ID. Sign into your wolfram account to generate one.

app_id <- "" 
wa <- WolframClient(app_id)

Ask a simple question

result <- wa$query("pi")
## Querying wolfram alpha...
library(knitr)
kable(result$get_plaintext(), format = "html")
pod id plaintext
Input Input pi
Decimal approximation DecimalApproximation 3.1415926535897932384626433832795028841971693993751058...
Property Property pi is a transcendental number
Number line NumberLine
Continued fraction ContinuedFraction [3; 7, 15, 1, 292, 1, 1, 1, 2, 1, 3, 1, 14, 2, 1, 1, 2, 2, 2, 2, 1, 84, 2, 1, 1, 15, ...]
Alternative representations AlternativeRepresentations:MathematicalFunctionIdentityData pi = 180 °
Alternative representations AlternativeRepresentations:MathematicalFunctionIdentityData pi = -i log(-1)
Alternative representations AlternativeRepresentations:MathematicalFunctionIdentityData pi = cos^(-1)(-1)
Series representations SeriesRepresentations:MathematicalFunctionIdentityData pi = 4 sum_(k=0)^infinity (-1)^k/(2 k+1)
Series representations SeriesRepresentations:MathematicalFunctionIdentityData pi = -2+2 sum_(k=1)^infinity 2^k/(binomial(2 k, k))
Series representations SeriesRepresentations:MathematicalFunctionIdentityData pi = sum_(k=0)^infinity (50 k-6)/(2^k binomial(3 k, k))
Integral representations IntegralRepresentations:MathematicalFunctionIdentityData pi = 2 integral_0^infinity 1/(t^2+1) dt
Integral representations IntegralRepresentations:MathematicalFunctionIdentityData pi = 4 integral_0^1 sqrt(1-t^2) dt
Integral representations IntegralRepresentations:MathematicalFunctionIdentityData pi = 2 integral_0^infinity (sin(t))/t dt

Ask a more specific question

result <- wa$query("ion equivalents of zinc chloride")
## Querying wolfram alpha...
kable(result$get_plaintext(), format = "html")
pod id plaintext
Input interpretation Input zinc chloride | ion equivalents
Result IonProperties:ChemicalData Zn^(2+) (zinc) | 1 Cl^(-) (chloride) | 2
#' Basic Wolfram Alpha client and result objects
library(XML)
library(plyr)
WolframClient <- setRefClass(
"WolframClient",
fields = list(
app_id = "character"
),
methods = list(
initialize = function(app_id) {
"initialize Wolfram Alpha Client"
app_id <<- app_id
},
query = function(query, quiet = TRUE) {
"run a query against the wolfram alpha database"
message("Querying wolfram alpha...")
wa_url <- paste0("http://api.wolframalpha.com/v2/query?input=",
URLencode(query), "&appid=", app_id)
destfile <- tempfile()
download.file(wa_url, destfile, method = "wget", quiet = quiet)
result <- WolframResult(xmlInternalTreeParse(destfile))
info <- result$get_info()
if (info$success != "true" || info$error != "false")
stop("There was a problem with this query. Please check the query infos:\n",
paste(paste(names(info), info, sep = " = "), collapse = "\n"))
return(result)
}
)
)
WolframResult <- setRefClass(
"WolframResult",
fields = list(
doc = "XMLInternalDocument"
),
methods = list(
initialize = function(doc) {
doc <<- doc
},
xml = function() doc,
get_info = function() {
as.list(xpathApply(doc, "//queryresult", xmlAttrs)[[1]])
},
get_pods = function() {
xpathApply(doc, "//pod")
},
get_plaintext = function() {
ldply(get_pods(), function(pod) {
data.frame(
pod = xmlGetAttr(pod, "title"),
id = xmlGetAttr(pod, "id"),
plaintext = unlist(xpathApply(pod, "subpod/plaintext", xmlValue))
)
})
}
)
)
@bmazoure
Copy link

Hey, that's a super useful bridge between WA and R. I thought this would be great to package up and upload on CRAN for convenience. Here, I changed it slightly and pushed a packaged version of this script on Git.

It would be great if you could upload this either to CRAN or your Git, so that people can just install_github() or install() ! Here: https://github.com/ArtificialBreeze/wolfRamalpha (tested, works as is)

@stefanavey
Copy link

Has this been wrapped up into a package? If not, I'd be happy to help get it there as I think it's very useful

@sebkopf
Copy link
Author

sebkopf commented Feb 16, 2020

please feel free to wrap it into a small package for CRAN submission, that'd be fantastic. there might be some overlap with the https://cran.r-project.org/web/packages/websearchr/index.html package but see for yourself and decide whether this would be non-redundant functionality

@mathzero
Copy link

This is very useful, much appreciated

@davan690
Copy link

Did this get added to CRAN? Happy to help out if needed as using this a bit at the mo. :)

@sebastian-c
Copy link

sebastian-c commented Apr 6, 2023

I had trouble with download.file on Windows:

Error during wrapup: 'wget' call had nonzero exit status
Error: no more error handlers available (recursive errors?); invoking 'abort' restart

However, using httr works instead works fine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment