将聚合结果转换为汇总表[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

给定此数据帧,该数据帧是对数据进行总和聚合的结果。 enter image description here

如何将其转换为通常的表格作为table的一个结果,以便正确地绘制它。

为了更清晰地了解所需的输出,它应该是这样的:

              Mountain Bikes          Road Bikes  
2005          130694                  708713  
2006          168445                  1304031   
2007          0                       56112  

我甚至尝试了一些愚蠢的事情,比如单独计算价值,然后将它但它仍然是一个数据框,所以它认为第一列是值而不是标题。

r
1个回答
0
投票

使用dplyrtidyr的解决方案。

library(dplyr)
library(tidyr)

dat2 <- dat %>%
  group_by(Category, Year) %>%
  summarize(SUM = sum(x)) %>%
  spread(Category, SUM, fill = 0)
dat2
# # A tibble: 3 x 3
#    Year `Mountain Bikes` `Road Bikes`
#   <dbl>            <dbl>        <dbl>
# 1  2005           130694       708713
# 2  2006           168445      1304031
# 3  2007                0       561122

数据

dat <- data.frame(Category = paste(c("Mountain", "Road", "Mountain", 
                                     "Road", "Road"), "Bikes", sep = " "),
                  Year = c(2005, 2005, 2006, 2006, 2007),
                  x = c(130694, 708713, 168445, 1304031, 561122))
© www.soinside.com 2019 - 2024. All rights reserved.