我有一長串列,并將分數列中的值合并為一列。但是,我不想將它們全部輸入,我只想在粘貼函式中使用 contains("test") ——這可能嗎?
這是我的資料以及我希望它的樣子:
library(dplyr)
#What I have :(
test <- tibble(id = c(1:2),
test_score = c(4,5),
test_building = c("Lupton", "Hearst"),
initials = c("s", "j"))
#What I want ^_^
answer <- tibble(id = c(1:2),
test_score = c(4,5),
test_building = c("Lupton", "Hearst"),
initials = c("s", "j"),
test_combo = c("4, Lupton", "5, Hearst"))
這是我嘗試過的一些失敗嘗試的墓地:
test %>%
mutate(test_combo = paste(vars(contains("test"))))
test %>%
mutate(test_combo = paste(across(contains("test"))))
我希望順序是 test_score,然后是 test_building,但順序真的沒那么重要,所以我會采用一個簡單的解決方案,以“錯誤”的順序正確粘貼它們,而不是用非常復雜的路徑將它們放入'正確的順序。
uj5u.com熱心網友回復:
一個復雜的解決方案可能是:
library(tidyr)
library(dplyr)
test %>%
mutate(across(starts_with("test_"), as.character)) %>%
pivot_longer(starts_with("test_")) %>%
group_by(id, initials) %>%
summarise(test_combo = paste(value, collapse = ", "), .groups = "drop") %>%
right_join(test, by = c("id", "initials"))
這回傳
# A tibble: 2 x 5
id initials test_combo test_score test_building
<int> <chr> <chr> <dbl> <chr>
1 1 s 4, Lupton 4 Lupton
2 2 j 5, Hearst 5 Hearst
一個簡單的方法可能是
test %>%
group_by(id) %>%
mutate(test_combo = paste(across(contains("test")), collapse = ", ")) %>%
ungroup()
回傳
# A tibble: 2 x 5
id test_score test_building initials test_combo
<int> <dbl> <chr> <chr> <chr>
1 1 4 Lupton s 4, Lupton
2 2 5 Hearst j 5, Hearst
uj5u.com熱心網友回復:
我們可以將pastewithacross與.names引數和unite函式結合使用:
library(dplyr)
library(tidyr)
test %>%
mutate(across(contains("test"), ~paste(.), .names ="new_{.col}")) %>%
unite(test_combo, starts_with('new'), na.rm = TRUE, sep = ', ')
id test_score test_building initials test_combo
<int> <dbl> <chr> <chr> <chr>
1 1 4 Lupton s 4, Lupton
2 2 5 Hearst j 5, Hearst
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/451119.html
上一篇:Resilience4j如何路由到回退方法,然后在特定時間后回傳原始方法
下一篇:沒有非字母符號的反向字串
