Frequency of values per column in table

前端 未结 4 1055
傲寒
傲寒 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:26

    library(tidyverse)
    
    dt <- data.frame(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))
    
    dt2 <- dt %>%
      mutate(ID = 1:n()) %>%
      gather(Group, x, -ID) %>%
      select(-ID) %>%
      mutate(Group = paste(Group, "n", sep = "_")) %>%
      count(Group, x) %>%
      spread(Group, n, fill = 0L)
    

提交回复
热议问题