使用dplyr替换基于条件的值

使用dplyr替换基于条件的值,r,dplyr,R,Dplyr,我对dplyr比较陌生,如果给定的列只包含0和1,我会尝试替换所有列的值 df <- data.frame(a=c(1,2,3,4), b=c(1,1,0,0), c=c(1,1,1,0)) df我们可以用all换行,在mutate\u if中返回长度为1的逻辑向量,然后执行recode df %>% dplyr::mutate_if(~ all(. %in% 0:1), ~ dplyr::recode(., `1` = 'yes', `0` = 'no')) # a

我对dplyr比较陌生,如果给定的列只包含0和1,我会尝试替换所有列的值

df <- data.frame(a=c(1,2,3,4), b=c(1,1,0,0), c=c(1,1,1,0))

df我们可以用
all
换行,在
mutate\u if
中返回长度为1的逻辑向量,然后执行
recode

df %>% 
    dplyr::mutate_if(~ all(. %in% 0:1), ~ dplyr::recode(., `1` = 'yes', `0` = 'no'))
#  a   b   c
#1 1 yes yes
#2 2 yes yes
#3 3  no yes
#4 4  no  no

在OP的代码中,我们需要
~
来指定匿名函数

df %>% 
 dplyr::mutate_if(~(min(., na.rm=TRUE)==0 & max(., na.rm=TRUE)==1),  
            ~dplyr::recode(., `1`="yes", `0`="no"))
#  a   b   c
#1 1 yes yes
#2 2 yes yes
#3 3  no yes
#4 4  no  no
df%>%dplyr::mutate_if(~all(.%在%0:1中),~as.logical()
可能更短-虽然这不是OP要求的,但可能是他们想要的…;)
df %>% 
 dplyr::mutate_if(~(min(., na.rm=TRUE)==0 & max(., na.rm=TRUE)==1),  
            ~dplyr::recode(., `1`="yes", `0`="no"))
#  a   b   c
#1 1 yes yes
#2 2 yes yes
#3 3  no yes
#4 4  no  no