Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用with()从R数据帧访问任意列_R_Dataframe - Fatal编程技术网

使用with()从R数据帧访问任意列

使用with()从R数据帧访问任意列,r,dataframe,R,Dataframe,假设我有一个数据框,其中一列的名称存储在变量中。使用括号表示法很容易使用变量访问此列: df <- data.frame(A = rep(1, 10), B = rep(2, 10)) column.name <- 'B' df[,column.name] 在调用方的环境中有效地计算column.name。我如何才能充分延迟求值,使with()提供与括号中给出的结果相同的结果?使用“with”创建一个本地化的临时名称空间,在其中求值某个表达式。在上面的代码中,您没有传入表达式 例

假设我有一个数据框,其中一列的名称存储在变量中。使用括号表示法很容易使用变量访问此列:

df <- data.frame(A = rep(1, 10), B = rep(2, 10))
column.name <- 'B'

df[,column.name]

在调用方的环境中有效地计算
column.name
。我如何才能充分延迟求值,使
with()
提供与括号中给出的结果相同的结果?

使用“with”创建一个本地化的临时名称空间,在其中求值某个表达式。在上面的代码中,您没有传入表达式

例如:

data(iris)   # this data is in your R installation, just call 'data' and pass it in
通常,您必须在数据框中引用变量名,如下所示:

tx = tapply(iris$sepal.len, list(iris$species), mean)
除非您这样做:

attach(iris)
使用“attach”的问题是名称空间冲突的可能性,因此您必须记住调用“detach”

“与”一起使用更干净:

tx = with( iris, tapply(sepal.len, list(species), mean) )

因此,调用签名(非正式地)是:使用(data,function())

您可以使用
get

with(df, get(column.name))

这是
with()
的一个很好的总结,但是我想知道如何强制
column.name
的值成为所需的表达式。
with(df, get(column.name))