r - 如何选择所有列以及附加表达式

标签 r data.table

假设我开始

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 a list, each element of the list becomes a column in the resulting data.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/

相关文章:

r - data.table:在满足条件的其他行之前和之后选择n个特定行

r - ggtern - 刻面时扭曲的 hex bin 大小和形状

r - 使用移动平均或内核平滑对二进制变量进行平滑

R - 检查函数中对象是否存在

用于 DPLYR 分辨率的 R Data.Table 解决方案

具有多个变量输入的 R 自定义 data.table 函数

r - 源()不起作用 ("node stack overflow")

r - 通过使用涉及两列的两个单独的选择标准使用 dplyr 进行过滤

R data.table 按组从第 i 个元素到每个剩余元素的距离

r - 如何针对大型数据表优化 R 中的 for 循环