【问题标题】:R - dplyr - mutate_if multiple conditionsR - dplyr - mutate_if 多个条件
【发布时间】:2019-01-30 02:35:03
【问题描述】:

我想根据多个条件对列进行变异。例如,对于最大值为 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

现在当我尝试合并它们时

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

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

我错过了什么?

【问题讨论】:

    标签: r conditional dplyr


    【解决方案1】:

    必须使用names 而不是colnames

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

    【讨论】:

    • 它适用于 colnames df %&gt;% mutate_if(max(.)==10 &amp; str_detect(colnames(.), "xy"),as.character) %&gt;% str()。但是为什么不使用~max 而使用max
    【解决方案2】:

    更简洁的方法是使用来自 dplyr 的across

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-26
      • 1970-01-01
      • 2017-08-08
      • 2021-09-17
      • 2020-01-07
      • 2018-07-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多