rdplyrfactors

Working with factors: put two function into dplyr


I was just looking for a tidier way to get the output of the following data:

library(dplyr)
library(gapminder)

gapminder$continent %>% class() 
gapminder$continent %>% nlevels()
gapminder$continent %>% levels()
gapminder$continent %>% str()

It looks a bit repetitive, so I want to merge it into one line using dplyr, so I tried the following:

gapminder$continent %>% class() %>% nlevels() %>% levels() %>% str()
#AND
gapminder %>% summarise_at(vars(continent), list(class = class, nlevels = nlevels,levels= levels))

but of course, those does not work. I am not sure how can I get the output.

The similar issue arises when I want to plot changing factors:

gapminder$continent = gapminder$continent %>%
  fct_relevel( "Oceania", "Europe")

gapminder %>%
  ggplot() +
  geom_bar(aes(fct_relevel( continent,"Africa", "Oceania"))) +
  coord_flip()+
  theme_bw() +
  labs(color = "country") 

Can I combine them together?


Solution

  • If we want to apply a set of functions, wrap it in a list

    library(gapminder)
    library(purrr)
    library(dplyr)
    map(list(class, nlevels, levels, str), ~ 
           gapminder %>%
             pull(continent) %>% 
             .x())