简体   繁体   English

R - dplyr - mutate_if 多个条件

[英]R - dplyr - mutate_if multiple conditions

I want to mutate a column based on multiple conditions.我想根据多个条件改变一列。 For example, for each column where the max is 5 and the column name contains "xy", apply a function.例如,对于最大值为 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

Now when I try to combine them现在当我尝试将它们结合起来时

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

Error in (~max(.) == 10) & (str_detect(colnames(.), "xy")) : operations are possible only for numeric, logical or complex types (~max(.) == 10) & (str_detect(colnames(.), "xy")) 中的错误:操作仅适用于数字、逻辑或复杂类型

What am I missing?我错过了什么?

必须使用names而不是列colnames

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

更简洁的方法是使用跨越从dplyr

df4 <- df %>% mutate(across(c(where(function(x)max(x)==10),contains('xy')),as.character))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM