4

I am running a simple R script in python using the following code.

import rpy2.robjects as robjects
r=robjects.r
output = r.source("sample.R")

Now when I print the output

print (output)

I am getting script's last variable only as an output and not all the variable (which I was not expecting. Also I was thinking if I call c or data, the results will be printed as such but python isn't identifying these variables coded in R). I am not sure how to call all these variables.

I am writing very simple code in R script just for testing. My R script looks like:

a <- 1
b <- 3
c <- a + b 
data = 1:20

now on calling the script and printing the results I am getting these the following at output. I am not sure what's happening.

$value

 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20



$visible

[1] FALSE

I am not sure how to exactly print variable as it is from R to python. Please guide me to it. Your help will be appreciated.

Regards

Jaws
  • 65
  • 2
  • 8

1 Answers1

6

Your variable output will only store the output from the source file, which is exactly what you get, id est the last variable. But all the variables actually live somewhere, in an R environment, which you can get with robjects.globalenv. Knowing that you can easily retrieve the value for each variable that you created in R:

import rpy2.robjects as robjects
robjects.r.source("sample.R")
print(robjects.globalenv["a"])
print(robjects.globalenv["b"])
print(robjects.globalenv["c"])
print(robjects.globalenv["data"])
kluu
  • 2,848
  • 3
  • 15
  • 35
  • how we'll deal with the R scripts if we have packages in them? – Jaws Apr 22 '18 at 09:46
  • U mean like using a function from an R package ? – kluu Apr 22 '18 at 12:13
  • means there is work in R script using different packages (that was done in R). Now if we call this script in python by method you told me. There appears an error related to packages as unknown – Jaws Apr 26 '18 at 12:15