R-将列名传递到data.table公式中-get和eval之间的差异
我有R-将列名传递到data.table公式中-get和eval之间的差异,r,data.table,R,Data.table,我有数据的列名称。表存储在变量中。我需要通过这些变量引用列。我使代码正常工作(下面的示例),但我不知道为什么有时需要使用get()和eval()。有人能澄清一下吗 # generate some data foo <- rep(1:2,each = 3) bar <- rep(c("A","B","C"),2) baz <- rep(1:5,2)[1:6] df <- data.frame(foo,bar,baz) setDT(df) # refer to column
数据的列名称。表存储在变量中。我需要通过这些变量引用列。我使代码正常工作(下面的示例),但我不知道为什么有时需要使用get()
和eval()
。有人能澄清一下吗
# generate some data
foo <- rep(1:2,each = 3)
bar <- rep(c("A","B","C"),2)
baz <- rep(1:5,2)[1:6]
df <- data.frame(foo,bar,baz)
setDT(df)
# refer to columns directly by their names
df[, "qux":=baz-baz[bar=="C"], by=foo]
# save column names into variables and call columns via these variables
var1 <- "foo"
var2 <- "bar"
var3 <- "baz"
varNew <- "qux2"
df[, eval(varNew) := get(var3) - get(var3)[get(var2) == "C"], by = get(var1)]
df
foo bar baz qux qux2
1: 1 A 1 -2 -2
2: 1 B 2 -1 -1
3: 1 C 3 0 0
4: 2 A 4 3 3
5: 2 B 5 4 4
6: 2 C 1 0 0
#生成一些数据
foo此示例显示了eval
和get
在功能上的差异。不需要使用data.table
对象来显示每个对象的功能
iVec <- c(123, 456)
iVarName <- "iVec"
# Returns the contents of 'iVarName' (a string). This happens
# to be the name of a variable but doesn't have to.
eval(iVarName)
##> [1] "iVec"
# Returns the contents of what 'iVarName' refers to (it
# refers to the variable "iVec" in this case, which
# is a variable which contains a vector of integers).
get(iVarName)
##> [1] 123 456
### #########################################
### Similar to above but where the variable
### 'iVec2' does not exist.
### #########################################
rm(iVec2)
# The variable "iVec2" does not exist.
iVarName2 <- 'iVec2'
# Returns the contents of 'iVarName2' (a string). This is not
# the name of an existing variable in this context.
eval(iVarName2)
## [1] "iVec2"
get(iVarName2) # Returns an error because 'iVec2' doesn't exist.
## Error in get(iVarName2) : object 'iVec2' not found
iVeceval(varNew)
返回单个字符串qux2
,get(var1)
返回var1
中的所有值;在这种情况下,var1
是“foo”,因此get(var1)
返回“foo”中的值。换句话说,在您的示例中,eval
返回单个字符串,get
返回每个列的值。您不需要使用by=get(.)
asby
argument接受列的字符向量在许多情况下,您还可以通过使用bquote构建整个表达式,然后对其求值来回避整个问题