Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error using dplyr::count() within purrr::map()

Tags:

r

dplyr

purrr

In this example I want to apply the count() function to every character variable in a dataset.

library(dplyr)
library(purrr)

nycflights13::flights %>% 
    select_if(is.character) %>% 
    map(., count)

But I receive the error message:

Error in UseMethod("groups") : no applicable method for 
'groups' applied to an object of class "character"

I'm not sure how to interpret the error message or update my code. Similar code works for numeric variables, but factor variables produce a similar error message to character variables

nycflights13::flights %>% 
    select_if(is.numeric) %>% 
    map(., mean, na.rm = TRUE)

nycflights13::flights %>% 
    select_if(is.character) %>% 
    mutate_all(as.factor) %>% 
    map(., count)
like image 428
Joe Avatar asked Dec 17 '22 23:12

Joe


1 Answers

If you want a list of tibbles with value counts, you can use

nycflights13::flights %>% 
  select_if(is.character) %>% 
  map(~count(data.frame(x=.x), x))
like image 163
MrFlick Avatar answered Jan 05 '23 05:01

MrFlick