Frequency of values per column in table

前端 未结 4 1035
傲寒
傲寒 2020-12-21 07:59

What is a good way to get the independent frequency counts of multiple columns using dplyr? I want to go from a table of values:

# A tibble: 7          


        
4条回答
  •  情话喂你
    2020-12-21 08:41

    library(dplyr)
    library(reshape2)
    df %>%
      melt() %>%
      dcast(value ~ variable, fun.aggregate=length)
    
    #   value a b c d
    # 1     1 2 0 2 1
    # 2     2 1 4 2 0
    # 3     3 2 2 0 6
    # 4     4 0 1 2 0
    # 5     5 2 0 1 0
    

    Data

    df <- structure(list(a = c(1L, 1L, 2L, 3L, 3L, 5L, 5L), b = c(2L, 2L, 
    2L, 2L, 3L, 3L, 4L), c = c(1L, 1L, 5L, 4L, 2L, 4L, 2L), d = c(3L, 
    3L, 3L, 3L, 3L, 3L, 1L)), .Names = c("a", "b", "c", "d"), class = "data.frame", row.names = c("1", 
    "2", "3", "4", "5", "6", "7"))
    

提交回复
热议问题