combining 2 dataframes, replacing values of one frame with other R

42 views Asked by At

Maybe this is easy, but I can't figure out a way to do this. My real issue is with a much larger data set, so I'm looking for something more elegant than what I'm currently doing.

I have 2 data frames. One has data (d1):

d1<-data.frame(id=(letters[1:10]), a=(rep(c(0,1), times=5)), b=(rep(c(0,1), times=5)))

The other is an index for times when a 0 in the first dataset should be an NA

d2<-data.frame(id=(letters[1:10]), a=c(NA,1, 0,1, NA,1, 0, 1, NA, 1), b=c(NA,1, 0,1, NA,1, 0, 1, NA, 1))

I am looking for a way to put an NA into d1, for any place where there is an NA in d2.

I can do it individually by column, but wondered if there was something easier!

nas<-which(is.na(d2$a))
    d1$a[nas]<-NA 

nas<-which(is.na(d2$b))
    d1$b[nas]<-NA 
1

There are 1 answers

1
Glen_b On BEST ANSWER

Try something like this

 d1[is.na(d2)] <- NA