John
John

Reputation: 1947

Change numbers in data frame depending on another data frame

Let's consider two data frames. One containing only zeroes and ones and second one with some random data. I want to set NA in second data frame when there is 1 in first data frame in the same place (in the same row and column) and do nothing if it's 0.

#Example
set.seed(20)
df1=data.frame(sample(0:1,3,replace=T),sample(0:1,3,replace=T),sample(0:1,3,replace=T))
df2=data.frame(rnorm(3),runif(3),rexp(3))
df1 
1 1 1 
0 1 0
0 0 1
df2 
        rnorm.3.  runif.3.   rexp.3.
1 -0.3316559 0.4520996 0.8501966
2  0.6992316 0.3221473 0.6389130
3  0.6520083 0.1090714 0.7141194
#My goal is to have 
df3 
NA                   NA             NA
0.6992316            NA             0.6389130
0.6520083            0.1090714      NA

Do you know how it can be done ? I tried to do something like this - take all coordinates from first data frame of ones. Then say that second data frame should have NA's one the same coordinates. But I'm not sure how should I extract those coordinates and refer to it in another data frame. Is there any simpler solution ?

Upvotes: 0

Views: 38

Answers (1)

Kian
Kian

Reputation: 110

You want to add NA instead of 1 in df2 which df1 == 1.

 set.seed(20)
> df1=data.frame(sample(0:1,3,replace=T),sample(0:1,3,replace=T),sample(0:1,3,replace=T))
> df2=data.frame(rnorm(3),runif(3),rexp(3))
> df2[df1==1] <- NA
> df2
   rnorm.3.  runif.3.  rexp.3.
1        NA        NA       NA
2 0.6992316        NA 0.638913
3 0.6520083 0.1090714       NA

Upvotes: 1

Related Questions