在dplyr中给定条件更改多个列值 [英] changing multiple column values given a condition in dplyr

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

问题描述

我正在寻找一种简单的方法来执行以下操作,但是使用dplyr,基本上是在满足条件时用NA替换3列中的值。

I'm looking to find a simple way to do something like the following but with dplyr, essentially just replacing the values in 3 columns with NA when the condition is met.

dta[dta$na.ind == 1, c('x1', 'x2', 'x3')] <- NA

我可以想到的唯一使用dplyr的方法是以下方法,但我认为应该有一种更简单的方法

The only method I can think of using dplyr is the following, but I feel there should be a simpler way

dta <- dta %>% 
    mutate(x1 = ifelse(na.ind == 1, NA, x1),
           x2 = ifelse(na.ind == 1, NA, x2),
           x3 = ifelse(na.ind == 1, NA, x3))

谢谢!

推荐答案

您可以使用 mutate_at 并将列 x1,x2,x3 传递给 .vars 参数:

You can use mutate_at and pass the columns x1,x2,x3 to .vars parameter:

dta <- data.frame(na.ind = 1:3, x1 = 2:4, x2 = 2:4, x3 = 2:4, x4 = 2:4)
dta
#  na.ind x1 x2 x3 x4
#1      1  2  2  2  2
#2      2  3  3  3  3
#3      3  4  4  4  4

dta %>% mutate_at(.vars = c("x1", "x2", "x3"), funs(ifelse(na.ind == 1, NA, .)))
#  na.ind x1 x2 x3 x4
#1      1 NA NA NA  2
#2      2  3  3  3  3
#3      3  4  4  4  4

这篇关于在dplyr中给定条件更改多个列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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