R-dplyr-mutate_if有多个条件 [英] R - dplyr - mutate_if multiple conditions

查看:1702
本文介绍了R-dplyr-mutate_if有多个条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想基于多个条件对一列进行突变.例如,对于最大为5且列名包含"xy"的每一列,应用一个函数.

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)

(〜max(.)== 10)&中的错误(str_detect(colnames(.),"xy")): 操作仅适用于数字,逻辑或复杂类型

Error in (~max(.) == 10) & (str_detect(colnames(.), "xy")) : operations are possible only for numeric, logical or complex types

我想念什么?

推荐答案

必须使用names代替colnames

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

这篇关于R-dplyr-mutate_if有多个条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆