R - 像数据一样转动

时间:2017-11-16 12:28:59

标签: r tidyverse

使用R和tidyverse库我试图实现像结果一样的枢轴。这里是样本数据集:

zz <- "   Date          ParAB ParCD
1         2017-05-27    A     C
2         2017-05-27    B     D
3         2017-05-27    A     D     
4         2017-05-27    B     C     
5         2017-05-27    B     C     
6         2017-05-28    A     D     
7         2017-05-28    A     C     
8         2017-05-28    A     C
9         2017-05-28    A     D"

Data <- read.table(text=zz, header = TRUE)}

我想将数据转换为每天的出现次数:

Date           A        B        C       D
2017-05-27     2        3        3       2
2017-05-28     2        0        1       1

我厌倦了在ParAB列上运行良好的扩散功能。

Data %>%
  group_by(Date, ParAB, ParCD) %>%
  summarise(occr = n()) %>%
  spread(ParAB, occr, fill = 0) %>%
  mutate(occrCD = A+B)

所以结果是:

# A tibble: 4 x 5
# Groups:   Date [2]
    Date        ParCD     A     B   occrCD
  <fctr>        <fctr> <dbl> <dbl>  <dbl>
1 2017-05-27      C     1     2      3
2 2017-05-27      D     1     1      2
3 2017-05-28      C     2     0      2
4 2017-05-28      D     2     0      2

然后当我尝试第二次传播它不能按预期工作。对于C和D行,特定日期不会添加A列(和B)列的数据。结果我得到了错误的数据。

两个步骤的代码:

Data %>%
  group_by(Date, ParAB, ParCD) %>%
  summarise(occr = n()) %>%
  spread(ParAB, occr, fill = 0) %>% # first spread - result as expected
  mutate(occrCD = A+B) %>%
  spread(ParCD, occrCD, fill = 0) %>% # second spread, lost sum for A and B
  group_by(Date) %>%
  summarise_all(sum)

并且结果不是我想要的。错误是可见的,因为A + B应该等于C + D但是对于2017-05-28它不是。 :(

# A tibble: 2 x 5
        Date     A     B     C     D
      <fctr> <dbl> <dbl> <dbl> <dbl>
1 2017-05-27     2     3     3     2
2 2017-05-28     2     0     2     2

我确信这是非常微不足道的,但是因为我很新,所以你的帮助非常受欢迎。

中号

1 个答案:

答案 0 :(得分:3)

如果将所有参数放在一列中,则没有理由spread两次。

library(dplyr)
library(tidyr)

zz <- "   Date          ParAB ParCD
1         2017-05-27    A     C
2         2017-05-27    B     D
3         2017-05-27    A     D     
4         2017-05-27    B     C     
5         2017-05-27    B     C     
6         2017-05-28    A     D     
7         2017-05-28    A     C     
8         2017-05-28    A     C
9         2017-05-28    A     D"

Data <- read.table(text=zz, header = TRUE, stringsAsFactors = F)


Data %>%
  gather(v1,value,-Date) %>%
  count(Date, value) %>%
  spread(value, n, fill = 0)

# # A tibble: 2 x 5
#         Date     A     B     C     D
# *      <chr> <dbl> <dbl> <dbl> <dbl>
# 1 2017-05-27     2     3     3     2
# 2 2017-05-28     4     0     2     2