You Are What You Decide: A Journey in Automation of Our Selves. |
While working with AdWords data in R, I wanted to get data from a Python function. In those situations, rPython package comes in handy. It lets you define and execute arbitrary Python function, and get the results.
install.packages("rPython", repos = "http://www.datanalytics.com/R")
Suppose you have a Python function that returns a JSON-like dictionary. Then can import it into an R data.frame as follows:
Note: it won't work if you are calling it from IPython. You should be using pure R.
library(rPython) python.exec(c("def somefunc():", "\treturn [{'campaignId1': {'cost': {'date1': 1, 'date2': 2}, 'qs': {'date1': 1, 'date2': 2}}}, {'campaignId2': {'cost': {'date1': 1, 'date2': 2}, 'qs': {'date1': 1, 'date2': 2}}}]")) y <- python.call("somefunc") a <- as.data.frame(y[[1]]$campaignId1) a qs cost date1 1 1 date2 2 2 b <- as.data.frame(y[[2]]$campaignId2) cbind(a,b) qs cost qs cost date1 1 1 1 1 date2 2 2 2 2
In the example, I used a function that returns a dictionary equivalent to the following JSON:
[ { "campaignId1": { "qs": { "date1": 1, "date2": 2 }, "cost": { "date1": 1, "date2": 2 } } }, { "campaignId2": { "qs": { "date1": 1, "date2": 2 }, "cost": { "date1": 1, "date2": 2 } } } ]