我想將這行代碼推廣到 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這里需要它,但我無法讓它作業。
另外,我肯定需要準引號來獲取每次列內容之前的列名,例如gender_masculine。
uj5u.com熱心網友回復:
這是使用gatherand 的一種可能方法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 = "_")
)
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/368507.html
