【问题标题】:How to use tabulate in the tidyverse?如何在 tidyverse 中使用表格?
【发布时间】:2020-03-06 17:16:33
【问题描述】:

我想将那段旧代码转换为 tidyverse。有人可以帮忙吗?

library(plyr)
ddply(dat,.(sex),function(x) tabulate(x[,1],nbins=5))

# result
#     sex V1 V2 V3 V4 V5
#1 female  1  6  0  2  0
#2   male  2 11  3  0  0

dat <- structure(list(P1 = c(2, 2, 1, 2, 2, 2, 2, 1, 2, 4, 3, 2, 3, 
2, 2, 2, 4, 2, 2, 1, 2, 3, 2, 2, 2), sex = structure(c(2L, 2L, 
2L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 
2L, 2L, 2L, 2L, 1L, 1L, 1L), .Label = c("female", "male"), class = "factor")), class = "data.frame", row.names = c(NA, 
-25L))

【问题讨论】:

    标签: r tidyverse


    【解决方案1】:
    library(tidyverse)
    
    # set number of bins
    nb = 5
    
    dat %>%
      count(P1, sex) %>%                                # count combinations
      complete(P1 = 1:nb, sex, fill = list(n = 0)) %>%  # if a bin is missing add a zero count
      spread(P1, n, sep = "_")                          # reshape dataset
    
    # # A tibble: 2 x 6
    #   sex     P1_1  P1_2  P1_3  P1_4  P1_5
    #   <fct>  <dbl> <dbl> <dbl> <dbl> <dbl>
    # 1 female     1     6     0     2     0
    # 2 male       2    11     3     0     0
    

    【讨论】:

    • 'retired' spread() 可以替换为:pivot_wider(names_from = P1, values_from = n, names_prefix = "P1_")
    【解决方案2】:

    base R中,我们可以在将'P1'列转换为factor后使用table

    table(transform(dat, P1 = factor(P1, levels = 1:5,
                 labels = paste0("P1_", 1:5)))[2:1])
    #       P1
    #sex      P1_1 P1_2 P1_3 P1_4 P1_5
    #  female    1    6    0    2    0
    #  male      2   11    3    0    0
    

    或者使用来自data.tabledcast

    library(data.table)
    dcast(setDT(dat), sex ~ factor(P1, levels = 1:5,
             labels = paste0("P1_", 1:5)), drop = FALSE, length)
    #      sex P1_1 P1_2 P1_3 P1_4 P1_5
    #1: female    1    6    0    2    0
    #2:   male    2   11    3    0    0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-17
      • 2020-05-24
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      • 2022-11-02
      • 2018-12-21
      相关资源
      最近更新 更多