假设我开始
mtcarsDT<-data.table(mtcars)
我想要相当于
mtcarsDT[,.(mpg, cyl, disp, hp, drat, wt, qsec, vs, am, gear, carb, newcol=myFunc())]
但我只想输入类似 mtcarsDT[,.(.SD, newcol=myFunc())
之类的简短内容,但这种语法当然行不通。
最佳答案
我通常的做法是
c(.SD, .(newcol = f())
这种方法在将函数应用于多个列时也很有用,例如
c(
g = lapply(.SD, g),
f = lapply(.SD, f),
.(N = .N)
)
这个语法有效是因为
- 返回值应该是一个列表(列);
.SD
已经是一个列表;c()
可用于组合列表;和.()
是list()
的别名,方便在DT[...]
中使用。
详细信息。来自 ?data.table
As long as
j
returns alist
, each element of the list becomes a column in the resultingdata.table
. This is the default enhanced mode.
类似的行在第一个小插图 vignette("datatable-intro")
中出现了两次,但不幸的是没有像 OP 这样的例子。 (也许应该添加一个?)
I don't really want to create a column, I just want to view the result of the expression next to the existing columns without having to save the column and then delete it later
对于这个用例,最好的解决方案可能是采用浅拷贝。该功能是 not available yet .
关于r - 如何选择所有列以及附加表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57208594/