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
If you're working with matrices, it's as simple as mat1[which(mat2 == 0)] <- NA.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With