我的问题与此问题有关:
Turn vector output into columns in data.table?
但我的情况有点复杂。我不仅将向量作为列返回,而且我还在同时计算其他列。 E.g:
DT = data.table(X = 1:10, Y = 11:20, Z = 21:30, group = rep(1:10, each = 3))
featuresDT <- quote(list(x = mean(X),
y = mean(Y),
z = mean(Z),
as.list(quantile(X))))
DT[, eval(featuresDT), by = "group"]
其中quantile
返回长度为5的向量。我没有获得包含8列的data.table,而是获得一个包含4列的数据,quantile
结果显示为额外行,x, y and z
重复5次。我也试过了dist = as.list(quantile(X)
,但是得到了相同但不同的列名。
答案 0 :(得分:3)
您应该将list
更改为c
。任何c
类型值的list
都会自动生成list
):
featuresDT <- quote(c(x = mean(X),
y = mean(Y),
z = mean(Z),
as.list(quantile(X))))
DT[, eval(featuresDT), by = "group"]
group x y z 0% 25% 50% 75% 100%
1: 1 2.000000 12.00000 22.00000 1 1.5 2 2.5 3
2: 2 5.000000 15.00000 25.00000 4 4.5 5 5.5 6
3: 3 8.000000 18.00000 28.00000 7 7.5 8 8.5 9
4: 4 4.333333 14.33333 24.33333 1 1.5 2 6.0 10
5: 5 4.000000 14.00000 24.00000 3 3.5 4 4.5 5
6: 6 7.000000 17.00000 27.00000 6 6.5 7 7.5 8
7: 7 6.666667 16.66667 26.66667 1 5.0 9 9.5 10
8: 8 3.000000 13.00000 23.00000 2 2.5 3 3.5 4
9: 9 6.000000 16.00000 26.00000 5 5.5 6 6.5 7
10: 10 9.000000 19.00000 29.00000 8 8.5 9 9.5 10
答案 1 :(得分:1)
试试这个:
featuresDT <- quote(cbind(list(x = mean(X),
y = mean(Y),
z = mean(Z)),
as.data.table(t(quantile(X)))))