dplyr: apply function table() to each column of a data.frame

后端 未结 4 692
小鲜肉
小鲜肉 2021-02-18 15:42

Apply function table() to each column of a data.frame using dplyr

I often apply the table-function on each column of a data frame using plyr, like this:

4条回答
  •  灰色年华
    2021-02-18 16:16

    You can try the following which does not rely on the tidyr package.

    mtcars %>% 
       lapply(table) %>% 
       lapply(as.data.frame) %>% 
       Map(cbind,var = names(mtcars),.) %>% 
       rbind_all() %>% 
       group_by(var) %>% 
       mutate(pct = Freq / sum(Freq))
    

提交回复
热议问题