我正在使用rpy2,并且需要在R对象上使用赋值方法。例如,从这个对象开始:

# Python code
from rpy2.robjects import r
myvar = r('c(a=1,b=2,c=3)')


假设我要分配给names(myvar)。 (注意:忽略rpy2提供了另一种通过myvar.names访问名称的方法。这仅适用于名称,不适用于任意赋值方法。)在R中,我可以这样做:

# R code
names(myvar) <- c("x", "y", "z")


但是,这在Python中不起作用:

# Python code
> names(myvar) = ['x', 'y', 'z']
In [62]: names(myvar) = ['x', 'y', 'z']
  File "<ipython-input-62-aa3f7998cdcb>", line 1
    names(myvar) = ['x', 'y', 'z']
                                  ^
SyntaxError: can't assign to function call


当然,我可以通过rpy2的字符串eval运行任意代码:

# Python code
r('''names(myvar) <- c("x", "y", "z")''')


但是将值插值到要评估的字符串中听起来并不有趣或安全。那么,有没有办法通过rpy2安全地完成method(object) <- value的等效操作?

最佳答案

在R中,“ setter”函数遵循命名约定,该约定使“ getter”的名称后跟<-。例如,当做

names(myvar) <- c("x", "y", "z")


正在发生以下情况:

myvar <- "names<-"(myvar, c("x","y","z"))


如果我们将其分解:

> myvar = c(a=1,b=2,c=3)
> # call the assignment function "names<-"
> "names<-"(myvar, c("x","y","z"))
x y z
1 2 3
> # the "names" are stored as an attribute
> attributes(myvar)
$names
[1] "x" "y" "z"
> attributes(myvar)$names <- c("a","b","c")
> myvar
a b c
1 2 3
> # note that the function does have a side effect
> # (unlike what I wrote in a previous version of this answer):
> # the names are changed in place. I think that this is a C-level
> # optimization specific to "names" and this may not always be
> # the case for all "setters"
> "names<-"(myvar, c("x","y","z"))
x y z
1 2 3
> myvar
x y z
1 2 3


从rpy2做类似method(object) <- value的事情很简单。 python代码如下所示:

set_method = r("`method<-`")
my_object = set_method(my_object, value)

关于python - 如何在rpy2中使用R的赋值方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38806898/

10-12 23:32