R - dplyr - mutate_if multiple conditions

余生颓废 提交于 2020-01-15 08:55:06

问题


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.

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

What am I missing?


回答1:


Had to use names instead of colnames

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


来源:https://stackoverflow.com/questions/51990450/r-dplyr-mutate-if-multiple-conditions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!