我想以编程方式根据谓词函数(例如is.character)和 "select helper"(例如starts_with("Z"))同时选择要变异的列.
library(dplyr)
df <- tibble(V1 = "a", V2 = 1, Z1 = "a", Z2 = 1)
Run Code Online (Sandbox Code Playgroud)
期望的输出(mutate_at(df, "Z1", paste, "b")但没有Z1明确选择):
structure(list(V1 = "a", V2 = 1, Z1 = "a b", Z2 = 1), class = c(
"tbl_df", "tbl", "data.frame"
), row.names = c(NA, -1L))
Run Code Online (Sandbox Code Playgroud)
换句话说,如何"组合" mutate_at(df, vars(starts_with("Z")), paste, "b")并mutate_if(df, is.character, paste, "b")在一个变异中?
为什么不使用两个步骤?
df %>%
select_if(is.character) %>%
select(starts_with("Z"))
Run Code Online (Sandbox Code Playgroud)
编辑:
select_if(df, is.character) %>%
select(starts_with("Z")) %>%
names() %>%
mutate_at(df, ., paste, "b")
Run Code Online (Sandbox Code Playgroud)
在较新版本的 tidyselect 和 dplyr 中,我们可以使用where将谓词函数转换为选择帮助器。
df %>%
mutate(across(where(is.character) & starts_with("Z"), paste, "b"))
#> # A tibble: 1 x 4
#> V1 V2 Z1 Z2
#> <chr> <dbl> <chr> <dbl>
#> 1 a 1 a b 1
Run Code Online (Sandbox Code Playgroud)
我们还必须使用较新的across界面,因为mutate_at与where.