首页 > 解决方案 > R 长到宽,计数和求和

问题描述

我有一个数据如下:

#dt
Method   ID     Source     Amt
A         1          X      10
A         1          Y      20
C         1          Z      30
B         2          Y      15
D         2          Z      10
C         3          X      20
D         3          X      20
E         4          Z      10
E         4          Z      10

我想要的是:

ID    Total_Amt     Method_A     Method_B     Method_C     Method_D     Method_E     Source_X     Source_Y     Source_Z 
1            60            2            0            1            0            0            1            1            1
2            25            0            1            0            1            0            0            1            1
3            40            0            0            1            1            0            2            0            0
4            20            0            0            0            0            2            0            0            2

对于MethodSource列,我想通过它们来计算计数,ID并使用它来转换为宽格式,并将列dcast加起来。AmtID

有什么帮助吗?

标签: rdata.tabledata-manipulationreshape2dcast

解决方案


这是使用dplyrtidyr库的一种方式。我们首先计算每个sumAmtID,以长格式获取数据,count行数并以宽格式返回。

library(dplyr)  
library(tidyr)

df %>%
  group_by(ID) %>%
  mutate(Amt = sum(Amt)) %>%
  pivot_longer(cols = c(Method, Source)) %>%
  count(ID, value, Amt, name) %>%
  pivot_wider(names_from = c(name, value), values_from = n, values_fill = 0)


#     ID   Amt Method_A Method_C Source_X Source_Y Source_Z Method_B Method_D Method_E
#  <int> <int>    <int>    <int>    <int>    <int>    <int>    <int>    <int>    <int>
#1     1    60        2        1        1        1        1        0        0        0
#2     2    25        0        0        0        1        1        1        1        0
#3     3    40        0        1        2        0        0        0        1        0
#4     4    20        0        0        0        0        2        0        0        2

推荐阅读