首页 > 解决方案 > R:在data.table中创建公式列时如何动态引用列?

问题描述

我正在尝试使用 data.table,但发现语法非常笨拙。

在我正在开发的应用程序中,我需要能够遍历各种功能并找到与每个功能对应的唯一列名。(没关系。我可以从 csv 查找文件中提取它,并将其作为字符串存储在循环的每次迭代中)。我遇到的问题是当我需要对其执行某种操作(即求和、均值等)时,在 data.table 语法中动态引用变量

在这种特殊情况下,我需要计算给定列的平均值。我使用 iris 数据集做了一个简单的例子。我需要能够通过变量引用列名。在这种情况下,我想找到 Sepal.Width 列的平均值而不直接引用它,而是通过变量 iris_var。

# The name of the column that we're interested in, stored as a string.
iris_var <- 'Sepal.Width'
# Data table.
iris_data <- as.data.table(iris)

# This works. Including "with=FALSE" allows the code to recognise Sepal.Width as the column name rather than a string.
iris_data[,iris_var, with=FALSE]

# This calculates the mean of Sepal.Width by referring to it directly. However, I need to be able to get this by referring to Sepal.Width dynamically via iris_var.
iris_data[,.(average=mean(Sepal.Width))]

# This does not work. 
iris_data[,.(average=mean(iris_var)), with=FALSE]

最后一行产生以下错误:

Error in `[.data.table`(iris_data, , .(average = mean(iris_var)), with = FALSE) : 
  When with=FALSE, j-argument should be of type logical/character/integer indicating the columns to select.
In addition: Warning message:
In mean.default(iris_var) :
  argument is not numeric or logical: returning NA

谁能告诉我我做错了什么?

标签: rdata.table

解决方案


推荐阅读