简体   繁体   中英

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

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

如果你正在使用矩阵,它就像mat1[which(mat2 == 0)] <- NA一样简单。

我找到了答案,在阅读了文档之后,我认为替换命令仅适用于向量,但以下是诀窍:

new.df <- replace(A.df, B.df == 0, "NaN")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM