【问题标题】:How to use table() with dplyr group by, map from purrr and a list of dataframes/tibbles)? (In R)如何使用 table() 与 dplyr group by,从 purrr 映射和数据帧/小标题列表)? (在 R 中)
【发布时间】:2020-06-06 23:54:08
【问题描述】:

问题 如何使用带有数据框/小标题列表的 table() 创建表,同时 按两个变量分组(例如:天序列(例如 {1,2,...,10})和因子 {0,1,2,3,4})

数据示例

example:
ldf<-lapply(1:30, function(x) as.data.frame(cbind(sample(1:3,10,replace=T), sample(1:3,10,replace=T), seq(1:5), sample(0:4,10,replace=T))))
example:

  [[1]]
   V1 V2 V3 V4
1   3  1  1  4
2   1  3  2  2
3   2  2  3  3
4   3  1  4  1
5   1  1  5  3
6   1  1  1  4
7   1  1  2  2
8   3  3  3  3
9   2  2  4  1
10  1  1  5  3

[[2]]
   V1 V2 V3 V4
1   2  1  1  2
2   3  1  2  0
3   1  1  3  4
4   3  1  4  0
5   2  1  5  0
6   2  2  1  2
7   2  2  2  0
8   2  2  3  4
9   2  1  4  0
10  2  3  5  3
...

其中 V1 和 V2 是我想要列出的过渡状态,例如。 table(df$V1, df$V2), & V3(当天)和 V4(0-4 之间的一个因素),我想分组。

预期输出

我想为 data.frame/tibbles 列表中的每个 data.frame/tibble 获取一个按 V3 和 V4 分组的表,并将其保存回另一个对象列表中。

visual example (not actual data)

data.frame 1 
group by v3=1 & v4=0
  1 2 3
1 0 1 2
2 0 3 4
3 4 5 6 

data.frame 1
group by v3=1 & v4=1
  1 2 3
1 1 7 8
2 2 6 9
3 4 5 0 

...

data.frame 1
group by v3=2 & v4=0
  1 2 3
1 5 4 4
2 6 5 3
3 7 8 4

...

data.frame 2

...

data.frame 3

...

etc...

【问题讨论】:

    标签: r group-by dplyr purrr


    【解决方案1】:

    我们可以splitdata.frame by 'V3', 'V4' 得到'V1', 'V2'的table

    lst2 <- lapply(ldf[1:2], function(dat) lapply(split(dat[1:2], 
                   dat[3:4], drop = TRUE), function(x) {
                     lvls <- sort(unique(unlist(x)))
                     table(factor(x[[1]], levels = lvls), factor(x[[2]], levels = lvls))
                      }))
    

    tidyverse,这里有一个选项

    library(purrr)
    library(tidyr)
    library(dplyr)
    map(ldf[1:2], ~
            .x %>%
               group_split(V3, V4) %>%
               map(~ .x %>% 
                     unite(V3V4, V3, V4) %>%
                     group_by_all %>% 
                     summarise(n = n()) %>% 
                     ungroup %>% 
                     complete(V1 = sort(unique(unlist(select(., V1, V2)))),
                              V2 = sort(unique(unlist(select(., V1, V2)))), 
                          fill = list(n = 0) )  %>%
                     pivot_wider(names_from = V2, values_from = n, 
                        values_fill = list(n = 0)) %>% 
                     fill(V3V4, .direction = "updown")))
    

    【讨论】:

      猜你喜欢
      • 2018-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-16
      • 1970-01-01
      • 2021-09-06
      • 1970-01-01
      • 2017-10-17
      相关资源
      最近更新 更多