r-如何在as.factor()中使用空格分隔的变量名来访问数据帧的数据



问题是何时出现的

我试图使用R的polr((方法(通过rpy2(进行有序回归分析,使用以下语句。在该声明中;步骤数";是我的因变量。当我(在列标题和语句中(设置下划线来替换空格(即Number_of_Steps(时,一切都很好。

model = mass.polr('as.factor(Number of Steps) ~ Var2',
data=df_data, method='logistic',
Hess = True)
# Here, mass = importr('MASS')

然而,使用空格(即"步数"(,我会得到以下错误。

RRuntimeError:解析错误(text=x,keep.source=FALSE(:
:17:意外符号1:as.factor(数量

我是如何解决这个问题的

我在谷歌上搜索过,也在SO中检查过与这个问题相关的不同问题(例如这个问题(。然而,我仍然没有找到这个问题的解决办法。

那么,我的问题

在使用mass.polr()时,如何在as.factor(variable name)中使用空格分隔的变量名(即列标题(?

感谢阅读!

这不是rpy2特有的。在R中,可以使用反勾号(`(来分隔包含空格的符号。

假设您的示例在其他方面是正确的,则应该使用以下方法:

model = mass.polr('as.factor(`Number of Steps`) ~ Var2',
data=df_data, method='logistic',
Hess=True)

演示:

import rpy2.robjects as ro
# Get an R data frame with a column name that has
# a space.
dataf = ro.r("""
require("MASS")
cbind(housing, "My Sat"=housing$Sat)
""")
print('column names:')
print(tuple(dataf.colnames))
from rpy2.robjects.packages import importr
mass = importr('MASS')
house_plr = mass.polr(
ro.Formula('as.factor(`My Sat`) ~ Infl + Type + Cont'),
data = dataf
)

最新更新