Reputation: 345
I have two data frames, one contains numbers, and the second is binary, both are the same size. I would now like to replace all numbers in data frame A with NA
if the corresponding variable in data frame B is 0 and not 1. If it is 1 the number should remain unchanged.
How do I go about that?
df A
A B C
1 34 32 12
2 52 23 34
df B
A B C
1 1 1 1
2 0 0 1
desired result
A B C
1 34 32 12
2 na na 34
Upvotes: 3
Views: 1659
Reputation: 345
I found my answer, after reading the docs I thought the replace command worked only for vectors, but the following does the trick:
new.df <- replace(A.df, B.df == 0, "NaN")
Upvotes: 6
Reputation: 44614
If you're working with matrices, it's as simple as mat1[which(mat2 == 0)] <- NA
.
Upvotes: 9