将选择的助手和谓词函数组合在dplyr中进行变异

Aur*_*èle 3 r dplyr

我想以编程方式根据谓词函数(例如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")在一个变异中?

F. *_*ivé 6

为什么不使用两个步骤?

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)

  • @Aurèle你可以在这个管道的末尾加上'%>%{mutate_at(df,names(.),paste,"b")}`来获得它.你必须在2个地方指定`df`,但我真的不认为在这种情况下可以解决这个问题. (3认同)

Aur*_*èle 1

在较新版本的 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_atwhere.