9

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

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))

Thanks!

Steve Reno
  • 1,304
  • 3
  • 14
  • 21

3 Answers3

7

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
Psidom
  • 209,562
  • 33
  • 339
  • 356
  • 5
    `funs()` is soft deprecated as of dplyr 0.8.0 and it is advised to use `~` instead: `dta %>% mutate_at(c("x1", "x2", "x3"), ~ ifelse(na.ind == 1, NA, .)))` – tic-toc-choc Oct 28 '19 at 17:33
5

Since scoped verbs like mutate_at, mutate_all etc. are being replaced by across, you could now make the following adjustments to Psidom's answer:

> 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(across(c(x1, x2, x3), ~ 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

See https://dplyr.tidyverse.org/reference/across.html for more information on across.

MOfTheWorld
  • 51
  • 1
  • 4
1

If you instead want a data.frame-wise replacement of a specific value (-99999) in any column for NA:

dat %>% mutate_all(funs(ifelse(.==-99999, NA, .)))
LmW.
  • 1,364
  • 9
  • 16
  • 2
    `mutate_if` operates on all rows of columns passing the predicate, not on subsets of rows. For example, you can `mutate_if(dat, is.character, as.factor)`. Of course, if you insist on using `mutate_if`, it is possible: `mutate_if(dat, is.numeric, funs(ifelse(.==-99999, NA, .)))` – LmW. Jul 23 '18 at 19:07
  • funs no longer works unfortunately as this solution was more intuitive than those below – Markm0705 Apr 23 '22 at 00:14