简体   繁体   English

为data.table R保留lapply(.SD,...)中的列名

[英]retaining column names in lapply(.SD,…) for data.table R

When applying a function with multiple output variables (eg, a list) to a subset of a data.table, I lose the variable names. 当将具有多个输出变量(例如,列表)的函数应用于data.table的子集时,我丢失了变量名称。 Is there a way to retain them? 有没有办法保留它们?

library(data.table)

foo <- function(x){
  list(mn = mean(x), sd = sd(x))
}

bar <- data.table(x=1:8, y=c("d","e","f","g"))

# column names "mn" and "sd" are replaced by "V1" and "V2"
bar[, sapply(.SD, foo), by = y, .SDcols="x"]

# column names "mn" and "sd" are retained
bar_split <- split(bar$x, bar$y)
t(sapply(bar_split, foo))

I would go wit the following, which is a bit awkward, but doesn't require writing the names manually no matter how many functions there are 我会想到以下内容,这有点尴尬,但不需要手动编写名称,无论有多少功能

bar[, as.list(unlist(lapply(.SD, foo))), by = y, .SDcols = "x"]
#    y x.mn     x.sd
# 1: d    3 2.828427
# 2: e    4 2.828427
# 3: f    5 2.828427
# 4: g    6 2.828427

The biggest advantage of this approach is that it binds the functions with the column names. 这种方法的最大优点是它将函数与列名绑定在一起。 If, for example, you would have an additional column, it will still give an informative result while using the same code as above 例如,如果您有一个额外的列,它仍然会在使用与上面相同的代码时提供信息性结果

set.seed(1)
bar[, z := sample(8)]
bar[, as.list(unlist(lapply(.SD, foo))), by = y, .SDcols = c("x", "z")]
#    y x.mn     x.sd z.mn      z.sd
# 1: d    3 2.828427  2.0 1.4142136
# 2: e    4 2.828427  7.5 0.7071068
# 3: f    5 2.828427  3.0 1.4142136
# 4: g    6 2.828427  5.5 0.7071068

The setNames function lets you add back the missing character vector.: setNames函数允许您添加缺少的字符向量:

bar[, setNames( sapply(.SD, foo), c("mn", "sd")), by = y, .SDcols="x"]
   y mn       sd
1: d  3 2.828427
2: e  4 2.828427
3: f  5 2.828427
4: g  6 2.828427

The authors suggested using the other form suggested by Arenburg: 作者建议使用Arenburg建议的另一种形式:

DT[, c('x2', 'y2') := list(x / sum(x), y / sum(y)), by = grp]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM