【问题标题】:Pivot Table grouped by year and month in R [closed]R中按年和月分组的数据透视表[关闭]
【发布时间】:2020-11-07 07:14:09
【问题描述】:

假设您有一个包含 6 列或更多列的数据框。

我想创建一个这样的数据透视表(这是在 Excel 中制作的)

如您所见,ID 是按年和月分类的,它们的“值”是求和。

我想在 R 中创建类似的东西(实际上不需要总数)。我已经尝试过 dplyr、tidyr 但我无法得到我想要的。

任何建议都会很有用

【问题讨论】:

标签: r excel pivot-table


【解决方案1】:

一个可能的解决方案是这样的:

library(dplyr)
library(tidyr)
# some test data I made up from you picture
df <- dplyr::tibble(ID = c("AS", "AS", "AD", "AF"),
                    Year = c(2019, 2019, 2019, 2019),
                    Month = c(1, 1, 1, 12),
                    Value1 = c(50, 60, 20, 30),
                    Value2 = c(40, 50, 10, 10),
                    Value3 = c(10, 15, 50, 65))
# calculations
df %>% 
  tidyr::pivot_longer(-c(ID, Year, Month), names_to = "Value_Group", values_to = "Value") %>% 
  dplyr::group_by(ID, Year, Month, Value_Group) %>% 
  dplyr::summarise(Value = sum(Value)) %>% 
  tidyr::pivot_wider(names_from = c(Year, Month, Value_Group), values_from = Value, values_fill = 0)


   ID    `2019_1_Value1` `2019_1_Value2` `2019_1_Value3` `2019_12_Value1` `2019_12_Value2` `2019_12_Value3`
  <chr>           <dbl>           <dbl>           <dbl>            <dbl>            <dbl>            <dbl>
1 AD                 20              10              50                0                0                0
2 AF                  0               0               0               30               10               65
3 AS                110              90              25                0                0                0    

【讨论】:

  • 我试过了,效果很好!!!非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-15
  • 1970-01-01
相关资源
最近更新 更多