摘要数据。按组显示变量

时间:2018-12-30 21:48:25

标签: r data.table

我想添加输出中汇总的变量

iris1 <- iris
setDT(iris1)
 iris1[, .(mean = lapply(.SD, mean,na.rm=TRUE), 
                         sd = lapply(.SD, sd,na.rm=TRUE)), 
                     by = Species, 
                     .SDcols=c("Sepal.Length","Sepal.Width","Petal.Length")] 

输出为

      Species  mean        sd
1:     setosa 5.006 0.3524897
2:     setosa 3.428 0.3790644
3:     setosa 1.462  0.173664
4: versicolor 5.936 0.5161711
5: versicolor  2.77 0.3137983
6: versicolor  4.26  0.469911
7:  virginica 6.588 0.6358796
8:  virginica 2.974 0.3224966
9:  virginica 5.552 0.5518947

我想要这样的东西

      Species  mean        sd      variable
1:     setosa 5.006 0.3524897  Sepal.Length
2:     setosa 3.428 0.3790644  Sepal.Width
3:     setosa 1.462  0.173664  Petal.Length
4: versicolor 5.936 0.5161711  Sepal.Length
5: versicolor  2.77 0.3137983  Sepal.Width
6: versicolor  4.26  0.469911  Petal.Length
7:  virginica 6.588 0.6358796  Sepal.Length
8:  virginica 2.974 0.3224966  Sepal.Width
9:  virginica 5.552 0.5518947  Petal.Length

0 个答案:

没有答案