简体   繁体   中英

Difference between `rpy2.robjects.r` and `rpy2.robjects.globalenv`

I was trying out rpy2 to call R code from python. While trying out some code, I realized that I can define an R function usin rpy2.robjects.r() (Notice () instead of [] , I am calling r ). Function defined this way can be indexed on both rpy2.robjects.r and rpy2.robjects.globalenv . However this does not seem to be the case with pi . I can do rpy2.robjects.r['pi'] but I cannot do rpy2.robjects.globalenv['pi'] :

robjects.r("""
    f <- function(){
        print("Hello World!!!")
    }
""")

#function f is defined using rpy2.robjects.r() and can be 
#accessed using rpy2.robjects.globalenv[]
#(as well as using rpy2.robjects.r[])

f = robjects.globalenv["f"]
print(f())      #Hello World!!!

#pi which can be accessed as rpy2.robjects.r[] cannot be 
#accessed as rpy2.robjects.globalenv[]

print(robjects.r['pi'])             #3.141593
print(robjects.globalenv['pi'])     #Error: object 'pi' not found

Why is it so?

The rpy2 object r is meant to represent "R" running embedded. You can pass it a string in a call (eg, r("1+2") ) and that string will be evaluated as R code and the output returned.

On the other hand, globalenv is the R "environment" .Globalenv . That's basically where objects go when you declare them in an R terminal. R code may make this clearer:

x <- 1
# get "x" back, the less-easy way
get("x", .GlobalEnv)

When doing pi in an R console, the symbol will be searched first in the .GlobalEnv, and if not found the rest of the "search path" (the loaded libraries) will be searched. pi is in the R package "base", IIRC.

pi # returns 3.14...
pi <- "abc"
pi # return "abc"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM