Search code examples
rplyrdplyr

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


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:

library(plyr)
ldply( mtcars, function(x) data.frame( table(x), prop.table( table(x) ) )  )

Is it possible to do this in dplyr also?

My attempts fail:

mtcars %>%  do( table %>% data.frame() )
melt( mtcars ) %>%  do( table %>% data.frame() )

Solution

  • Using tidyverse (dplyr and purrr):

    library(tidyverse)
    
    mtcars %>%
        map( function(x) table(x) )
    

    Or:

    mtcars %>%
        map(~ table(.x) )
    

    Or simply:

    library(tidyverse)
    
    mtcars %>%
        map( table )