tabulate using tabyl by grouping variable using group_split and group_map

Viewed 1007

To get a quick frequency (tabulate) of one column or multiple columns at the one time I use tabyl function like so:

library(janitor)
library(tidyverse)

#tabulate one column at a time
iris %>% 
  tabyl(Petal.Width)

#tabulate multiple columns at once using map
iris %>% 
  select(Petal.Width, Petal.Length) %>% 
  map(tabyl)

I'm trying to replicate these two cases but have the output by a grouping variable, Species in this example. I would like the simplest solution and I would like to try the newer group_split and group_map commands for this.

I have been able to produce a similar type output in a dataframe format (although a simple list that tabyl produces is what I want for the case of more than one variable):

#works 
iris %>%
  group_by(Species) %>%
  nest() %>% 
  mutate(out = map(data, ~ tabyl(.x$Petal.Width) %>% 
                     as_tibble)) %>% 
  select(-data) %>%
  unnest

This works but I would have thought it could be a bit more simple like my column method approach, I was thinking something like this for one column per grouping variable:

#by group for one column
iris %>% 
  group_by(Species) %>% 
  group_split() %>% 
  map(~tabyl(Petal.Width))

For multiple columns I'm not sure I need the select row here? Maybe group_map could simplify it in one line?

#by group for multiple columns
iris %>% 
  #do i need to select grouping variable and variables of interest?
  select(Species, Petal.Width, Petal.Length) %>% 
  group_by(Species) %>% 
  group_split() %>% 
  map(~tabyl())   #could I use group_map and select the columns at once?

Any suggestions please?

1 Answers
  iris %>% 
       #use split(.$Species) if you need a list with names 
       group_split(Species) %>% 
       map(~imap(.x %>%select(Species, Petal.Width, Petal.Length), 
                  function(x,y){
                          out <-tabyl(x)
                          colnames(out)[1]=y
                          out}))

If you jsut need the default column name for the first column, then you can do iris %>% group_split(Species) %>% map(~map(.x, tabyl))

Related