R - 将列名传递到 data.table 公式中 - get 和 eval 之间的区别

标签 r data.table

我将 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 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

最佳答案

此示例显示了 evalget 在功能上的区别。不需要使用 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

因为这个问题更多的是关于evalget,所以我将省略 data.table 细节。 data.table 处理字符串和变量名称的方式很可能在不同的 SO 帖子中得到回答。

关于R - 将列名传递到 data.table 公式中 - get 和 eval 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36667359/

相关文章:

r - 使用相当于 purrr:::map 来遍历 data.table

r - 使用 pROC 绘制 ROC 曲线失败

r - 为什么在 R Notebook 中设置工作目录不会更改控制台中的工作目录?

r - 在ggplot中使用相同的数据源覆盖两个geom_sf但变量类型不同

r - 带特殊字符的grep

performance - 如何使用 data.table 提高当前使用 ddply 的数据清理代码的性能?

r - 在数据表中创建包含更多行的新列

R 将 table() 的输出保存到数据框中

r - 如何从日期中获取周数?

r - 如何使用 data.tables 对多列进行高效的矢量化更新?