r - 在 R 中使用 data.table 制作函数
问题描述
我正在学习用库编写函数data.table
。经过实验,我曾经get()
将变量转换为对象。想知道是否有更多的实现方式?
library(data.table)
DT <- data.table(
V1=rep(letters[1:3],5),
V2=c(2:16)
)
Test1 <- DT[,.((V2-sd(V2))/(max(V2)-min(V2))), by=.(V1)] # for comparision
Norma <- function(dataset, Vari, group_by){
dataset[,
.((get(Vari)-sd(get(Vari)))/(max(get(Vari))-min(get(Vari)))),
by=.(get(group_by))
]
}
Test2 <- Norma(DT,"V2","V1")
它有效,Test1 与 Test2 相同。
解决方案
Instead of get
, we can specify the columns of interest where the function needs to be applied in .SDcols
and then loop through the columns. Here, it is only one column, so we extract that column as a vector using [[
Norma <- function(dataset, Vari, group_by){
dataset[,
.((.SD[[1]]-sd(.SD[[1]]))/(max(.SD[[1]])-min(.SD[[1]]))),
by= group_by, .SDcols = Vari
]
}
identical(Norma(DT, "V2", "V1"), Test1)
#[1] TRUE
推荐阅读
- c# - 如何在 View 中显示文章的作者?
- lotus-domino - 多个收件人 lotusscript 发送
- python - 有没有办法构建包含我的自定义 python 包和自动启动脚本的 OpenWrt 固件?
- regex - 如何将“退格字符”添加到 vscode 中的正则表达式输出更改?
- java - 为什么这个共同祖先解决方案具有更好的最坏情况性能?
- java - 无法创建与数据库的新连接
- python - 将我的自定义小部件连接到我的屏幕管理器
- web-scraping - 为什么我无法访问 tbody 中的信息?
- ruby - 将 Ruby 哈希转换并转换为人类可读的字符串
- javascript - jquery prop.(“disabled”,true) 不工作,也不是 .removeAttr('disabled');