r - 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
谁能告诉我我做错了什么?
解决方案
推荐阅读
- python-3.x - 我如何在另一个模型中添加注册数据并可以在 django 中从该数据登录
- reactjs - Firebase Deploy 显示一个反应应用程序的空白页面
- r - 使用 insertUI 创建不同类型的闪亮小部件
- azure - 如何使用 zip 文件和 ARM 模板将机器人框架应用程序部署到 azure?
- python - 如何从 python 中的响应标头中删除服务器名称(SimpleHTTPRequestHandler)
- python - Python 阶乘程序输出
- anylogic - Anylogic Image index change in simulation window
- flutter - Geolocator 使用具有链式等待异步方法的 distanceBetween() Flutter 给出错误的距离
- php - 如何通过带有爆炸功能的codeigniter将restfull api发布到数据库?
- javascript - 向下滚动到部分时使用anime.js动画菜单项