R - dplyr - mutate_if 多个条件

drj*_*122 3 r conditional-statements dplyr

我想根据多个条件改变列。例如,对于最大值为 5 并且列名称包含“xy”的每一列,应用一个函数。

df <- data.frame(
  xx1 = c(0, 1, 2),
  xy1 = c(0, 5, 10),
  xx2 = c(0, 1, 2),
  xy2 = c(0, 5, 10)
)
> df

xx1 xy1 xx2 xy2
1   0   0   0   0
2   1   5   1   5
3   2  10   2  10

df2 <- df %>% mutate_if(~max(.)==10, as.character)
> str(df2)
'data.frame':   3 obs. of  4 variables:
 $ xx1: num  0 1 2
 $ xy1: chr  "0" "5" "10"
 $ xx2: num  0 1 2
 $ xy2: chr  "0" "5" "10"
#function worked
df3 <- df %>% mutate_if(str_detect(colnames(.), "xy"), as.character)
> str(df3)
'data.frame':   3 obs. of  4 variables:
 $ xx1: num  0 1 2
 $ xy1: chr  "0" "5" "10"
 $ xx2: num  0 1 2
 $ xy2: chr  "0" "5" "10"
#Worked again
Run Code Online (Sandbox Code Playgroud)

现在当我尝试将它们结合起来时

df4 <- df %>% mutate_if((~max(.)==10) & (str_detect(colnames(.), "xy")), as.character)
Run Code Online (Sandbox Code Playgroud)

(~max(.) == 10) & (str_detect(colnames(.), "xy")) 中的错误:只能对数字、逻辑或复杂类型进行操作

我缺少什么?

drj*_*122 5

不得不使用names而不是colnames

df4 <- df %>% mutate_if((max(.)==10 & str_detect(names(.), "xy")), as.character)
Run Code Online (Sandbox Code Playgroud)