ViSa
ViSa

Reputation: 2237

How to get each vector / column name inside a map function in r?

I am new in R and applying a plotting function to see counts of all factors of each factor column.

df

install.packages("gapminder")
library(gapminder)

gapminder %>% head()

########### output ###############

country continent   year    lifeExp pop gdpPercap
<fct>   <fct>   <int>   <dbl>   <int>   <dbl>
Afghanistan Asia    1952    28.801  8425333 779.4453
Afghanistan Asia    1957    30.332  9240934 820.8530
Afghanistan Asia    1962    31.997  10267083    853.1007
Afghanistan Asia    1967    34.020  11537966    836.1971
Afghanistan Asia    1972    36.088  13079460    739.9811
Afghanistan Asia    1977    38.438  14880372    786.1134

Issue: I am not able to get the column name as chart title in below code:

gapminder %>% 
  select_if(is.factor) %>% 

  map(function(feature) {
    count(data.frame(x = feature), x) %>% 

  ggplot(aes(x = x, y = n)) +
  geom_col() +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 90)) +

  # issue here in getting column name as chart title
  labs(title = colnames(feature))

  # labs(title = colnames(x))
  })

It looks like small issue but not able to figure out how to get the respective column names for each chart

Upvotes: 1

Views: 157

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388982

You can use imap instead of map which will give you access to column names as well as values.

library(tidyverse)

list_plot <- gapminder %>% 
              select(where(is.factor)) %>%
              imap(function(feature_value, feature_name) {
                count(data.frame(x = feature_value), x) %>% 
                ggplot(aes(x = x, y = n)) +
                geom_col() +
                theme_minimal() +
                theme(axis.text.x = element_text(angle = 90)) +
                labs(title = feature_name)
              })

Upvotes: 1

Duck
Duck

Reputation: 39595

Maybe try this approach as an option for you. Reshape your data with the factor variables and then summarise to get the counts. Using facets can be of help when setting the titles for each variable. Here the code:

library(gapminder)
library(tidyverse)
#Code
gapminder %>% 
  select_if(is.factor) %>%
  pivot_longer(everything()) %>%
  group_by(name,value) %>%
  summarise(N=n()) %>%
  ggplot(aes(x = value, y = N)) +
  geom_col(fill='purple',color='black') +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 90)) +
  facet_wrap(.~name,nrow = 1,scales = 'free')

Output:

enter image description here

Upvotes: 2

Related Questions