Home > Mobile >  generalise a mutate to all columns of a tibble
generalise a mutate to all columns of a tibble

Time:11-29

I would like to generalise this line of code to all the columns of the tibble:

starwars_with_species_as_last_column <- starwars %>% 
  select(1:11) # not interested in generalising this

starwars_with_species_as_last_column %>% 
  transmute(text = str_c("gender_", gender, " homeworld_", homeworld, "\n", species))

So I'm thinking at a function that takes as input a tibble with n columns and applies n-1 times some concatenation col1name_col1content, col2name_col2content and a final time a different concatenation with the last column.

I think I can do it with a traditional if statement, iterating on all columns. But it would by much nicer to do it tidyverse style. I imagine purrr is needed here but I can't get it work.

Also, I surely need quasi-quotation to get everytime the column name before the column content, such as gender_masculine.

CodePudding user response:

Here is a possible approach using gather and paste:

starwars %>%
  select(1:11) %>%
  mutate(row = 1:n()) %>% 
  gather(coln, value, -row) %>%
  group_by(row) %>%
  summarise(
    text = paste(
      paste(coln[-n()], value[-n()], sep = "_", collapse = "_"), 
      "\n",
      paste(last(coln), last(value), sep = "_")
    )
  )
  • Related