Reputation: 33
I am new to r and I have been struggling to do the following. If one value ("y" in the example below) equals to 0, I want to change certain values ("x1" and "x2") to be NA, but leave others unchanged ("x3"). Example:
df <- data.frame(y=c(1,0,1,1,0,0,1,0,1,0), x1=c(NA,3,4,7,NA,8,2,NA,3,7), x2=c(1,NA,4,7,5,6,NA,2,3,1), x3=c(9,5,2,4,7,2,5,8,2,2))
I want the output to be:
y x1 x2 x3
1 1 NA 1 9
2 0 NA NA 5
3 1 4 4 2
4 1 7 7 4
5 0 NA NA 7
6 0 NA NA 2
7 1 2 NA 5
8 0 NA NA 8
9 1 3 3 2
10 0 NA NA 2
Upvotes: 3
Views: 396
Reputation: 31452
To do the replacement in 2nd and 3rd columns, you can use
df[df$y == 0, 2:3] <- NA
Or, to specify the columns by name
df[df$y == 0, c("x1", "x2")] <- NA
Alternatively, using library(data.table)
, we can do
setDT(df)[y==0, c('x1','x2') := NA]
Upvotes: 1
Reputation: 388797
We can use mutate_at
from dplyr
library(dplyr)
df %>%
mutate_at(vars(c("x1", "x2")), funs(replace(., y == 0, NA)))
# y x1 x2 x3
# 1 NA 1 9
#2 0 NA NA 5
#3 1 4 4 2
#4 1 7 7 4
#5 0 NA NA 7
#6 0 NA NA 2
#7 1 2 NA 5
#8 0 NA NA 8
#9 1 3 3 2
#10 0 NA NA 2
Upvotes: 2