4
votes

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)
1
What exactly do you expect the output to be? count() isn't meant to be used on character vectors -- you get the same error with count(letters[1:10]). - MrFlick
count is designed to work on a data frame, not a vector. - alistaire
@MrFlick I was hoping to view the counts of unique values for each character variable in my dataset. - Joe
You either want map(., table) or %>% count(.) but they perform different things - CPak
But what type of data structure were you expecting? A list of data.frames with two columns (value, count)? - MrFlick

1 Answers

11
votes

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))