一个矩阵,其中包含行中的变量和列中的计算

时间:2017-05-29 15:41:36

标签: r

我有一个我必须分析的数据框。

对于我的数据框的每一列,我会计算一些微积分,例如meanminmax

我希望将结果显示为这样的矩阵:

+--------+------+----+-----+-----+
|        | mean | sd | min | max |
+--------+------+----+-----+-----+
| age    | 55   | 10 | 22  | 89  |
+--------+------+----+-----+-----+
| height | 175  | 12 | 160 | 190 |
+--------+------+----+-----+-----+
| weight | 70   | 15 | 50  | 110 |
+--------+------+----+-----+-----+

我该怎么办?

1 个答案:

答案 0 :(得分:1)

一个选项是tidyverse

library(tidyverse)
d1 <- df1 %>%
        select(age, height, weight) %>%
        gather %>%
        group_by(key) %>% 
        summarise(mean = mean(value), sd = sd(value), min = min(value), max = max(value))
m1 <- as.matrix(d1[-1])
rownames(m1) <- d1[[1]]
m1
#          mean        sd       min       max
#age     29.72114 1.1530639  25.53044  31.51712 
#height 170.13357 0.9731242 168.43238 171.77091
#weight  59.69239 0.7826297  58.00708  61.05686

数据

set.seed(24)
df1 <- data.frame(col1 = rnorm(24), age = rnorm(24, 30), height = rnorm(24, 170),
         weight  = rnorm(24, 60))