假设我们有数据框
product qua color month
1 Box 3 red jan
2 Box 14 blue jan
3 Box 22 green jan
4 Box 10 red feb
5 Box 12 blue feb
6 Box 36 green feb
7 Box 31 red mar
8 Box 1 blue mar
9 Box 7 green mar
如何通过这种方式对数据进行分组:
jan feb mar
box red 3 10 31
blue 14 12 1
green 22 36 7
非常感谢)
答案 0 :(得分:0)
数据:
df<-
data.table::fread("id product qua color month
1 Box 3 red jan
2 Box 14 blue jan
3 Box 22 green jan
4 Box 10 red feb
5 Box 12 blue feb
6 Box 36 green feb
7 Box 31 red mar
8 Box 1 blue mar
9 Box 7 green mar")[,-1] %>% setDF
代码:
df %>%
mutate(color = factor(color,levels=unique(na.omit(color))), month = factor(month,levels=unique(na.omit(month)))) %>%
spread(month, qua)
结果:
product color jan feb mar
1 Box red 3 10 31
2 Box blue 14 12 1
3 Box green 22 36 7
只拥有一个盒子:
例如,将以上内容保存到result
。
result$product[duplicated(result$product)]<-""
新结果:
product color jan feb mar
1 Box red 3 10 31
2 blue 14 12 1
3 green 22 36 7
答案 1 :(得分:0)
您可以尝试dcast
中的reshape2
:
library(reshape2)
dcast(df, formula = product + color ~ month, value.var = 'qua', mean)
# product color feb jan mar
#1 Box blue 12 14 1
#2 Box green 36 22 7
#3 Box red 10 3 31
(如果问题将被标记为重复,将删除此答案。)