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

后端 未结 4 707
小鲜肉
小鲜肉 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:19

    Solution by Caner did not work but from comenter akrun (credit goes to him), this solution worked great. Also using a much larger tibble to demo it. Also I added an order by percent descending.

    library(nycflights13);dim(flights)
    
    tte<-gather(flights, Var, Val) %>% 
    group_by(Var) %>% dplyr::mutate(n=n()) %>% 
    group_by(Var,Val) %>% dplyr::mutate(n1=n(), Percent=n1/n)%>%
    arrange(Var,desc(n1) %>% unique()
    

提交回复
热议问题