我有一个看起来像这样的数据
df<- structure(list(time = structure(1:12, .Label = c("M11", "M12",
"M13", "M14", "M15", "M16", "M51", "M52", "M53", "M54", "M55",
"M56"), class = "factor"), grp = structure(c(1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "TT", class = "factor"),
X2 = c(36034L, 63763L, 51432L, 65100L, 61444L, 71012L, 266610L,
389787L, 47659L, 63156L, 84593L, 84331L), X3 = c(45632L,
66505L, 60360L, 36685L, 107551L, 53360L, 323952L, 344944L,
69601L, 51268L, 130665L, 59704L), X4 = c(59025L, 52837L,
68571L, 35788L, 75262L, 66601L, 424683L, 340948L, 79487L,
42809L, 95607L, 81739L), X5 = c(74767L, 48210L, 70972L, 67705L,
85576L, 89265L, 393380L, 306633L, 77816L, 73611L, 106317L,
116890L), X6 = c(50846L, 37970L, 63896L, 78296L, 81216L,
62308L, 62613L, 21770L, 80955L, 88832L, 97586L, 68345L),
X7 = c(26688L, 27830L, 17010L, 54074L, 26727L, 31109L, 24448L,
38701L, 17378L, 46327L, 25324L, 25325L)), class = "data.frame", row.names = c(NA,
-12L))
我正在尝试获取M1和M5中的两个的每一列的中位数。 我想获得M11,M12,M13,M14,M15,M16每列的中位数 然后是M51,M52,M53,M54,M55,M56
我尝试使用apply,但无法弄清楚
apply(df[,-c(1,2)], 1, function(x) tapply(x, df[,1], median))
我想要这样的格式
time grp 2 3 4 5 6 7
M1 TT1-6 62603.5 56860 62813 72869.5 63102 27278.5
M5 TT1-6 84462 100133 88673 111603.5 74650 25324.5
答案 0 :(得分:2)
我们可以使用tidyverse
。提取“时间”的子字符串,在group_by
中与“ grp”列一起使用,然后在所有列的“ median”和“ sd”中使用summarise_all
library(dplyr)
df %>%
group_by(time = substr(time, 1, 2), grp) %>%
summarise_all(funs(median, sd))