Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace values in df/matrix based on another matrix/df in R

Tags:

replace

r

matrix

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
like image 334
ShellfishGene Avatar asked Jan 23 '26 09:01

ShellfishGene


2 Answers

If you're working with matrices, it's as simple as mat1[which(mat2 == 0)] <- NA.

like image 118
Matthew Plourde Avatar answered Jan 26 '26 00:01

Matthew Plourde


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")
like image 24
ShellfishGene Avatar answered Jan 26 '26 00:01

ShellfishGene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!