Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

generalise a mutate to all columns of a tibble

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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 = "_")
    )
  )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading