Faster ways to calculate frequencies and cast from long to wide

前端 未结 4 920
灰色年华
灰色年华 2020-11-21 04:56

I am trying to obtain counts of each combination of levels of two variables, \"week\" and \"id\". I\'d like the result to have \"id\" as rows, and \"week\" as columns, and t

4条回答
  •  余生分开走
    2020-11-21 05:46

    A tidyverse option could be :

    library(dplyr)
    library(tidyr)
    
    df %>%
      count(id, week) %>%
      pivot_wider(names_from = week, values_from = n, values_fill = list(n = 0))
      #spread(week, n, fill = 0) #In older version of tidyr
    
    #     id   `1`   `2`   `3`
    #      
    #1     1     2     1     1
    #2     2     0     0     1
    

    Or using tabyl from janitor :

    janitor::tabyl(df, id, week)
    # id 1 2 3
    #  1 2 1 1
    #  2 0 0 1
    

    data

    df <- structure(list(id = c(1L, 1L, 1L, 1L, 2L), week = c(1L, 2L, 3L, 
    1L, 3L)), class = "data.frame", row.names = c(NA, -5L))
    

提交回复
热议问题