将变异推广到 tibble 的所有列

generalise a mutate to all columns of a 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))

所以我在考虑一个函数,该函数将具有 n 列的 tibble 作为输入,并应用 n-1 次一些串联 col1name_col1content、col2name_col2content 和最后一次与最后一列。

我想我可以用传统的 if 语句来完成,迭代所有列。但它会更好地做到 tidyverse 风格。我想这里需要 purrr,但我无法让它工作。

此外,我肯定需要 quasi-quotation 每次获取列内容之前的列名,例如 gender_masculine。

这是使用 gatherpaste 的可能方法:

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