简体   繁体   English

当R中的df2为1时,在df1中替换0

[英]Replace 0 in df1 when there is a 1 in df2 in R

I have 2 dataframes with the same number of columns and rows. 我有2个具有相同列数和行数的数据帧。 df1 is filled in with 0s and NAs and df2 has 1s and NAs. df1用0和NA填充,df2用1s和NA填充。 Wherever there is a 1 in df2, I would like it to also appear in df1 by replacing the 0 that is found in the same spot in df1. 只要df2中有1,我希望它也可以通过替换df1中相同位置的0来显示在df1中。 The actual dataframes have approx 5000 columns and 85 rows, so I am looking for a solution that I can easily run over the entire thing. 实际的数据帧有大约5000列和85行,所以我正在寻找一个可以轻松运行整个事物的解决方案。

df1 looks like this: df1看起来像这样:

       1    2   3   4   5   6   7   8   9   10    
stat1  NA   NA  NA  NA  NA  NA  NA  0   0   0
stat2  0    0   0   0   0   0   0   0   0   0
stat3  0    0   0   0   0   0   NA  NA  NA  NA
stat4  NA   NA  NA  NA  NA  NA  NA  NA  NA  NA
stat5  NA   NA  NA  0   0   0   0   0   0   0
stat6  NA   NA  0   0   0   0   0   0   NA  NA
stat7  0    0   0   0   0   0   0   0   0   0
stat8  NA   NA  NA  NA  NA  NA  NA  NA  NA  NA
stat9  NA   NA  NA  NA  NA  NA  NA  NA  NA  NA
stat10 NA   NA  NA  NA  NA  0   0   0   0   0

df2 looks like this: df2看起来像这样:

       1    2   3   4   5   6   7   8   9   10    
stat1  NA   NA  NA  NA  NA  NA  NA  NA  NA  1
stat2  1    NA  NA  NA  NA  NA  NA  NA  NA  NA
stat3  NA   NA  NA  1   NA  NA  NA  NA  NA  NA
stat4  NA   NA  NA  NA  NA  NA  NA  NA  NA  NA
stat5  NA   NA  NA  NA  NA  NA  NA  NA  NA  NA
stat6  NA   NA  NA  NA  1   NA  NA  NA  NA  NA
stat7  1    NA  NA  NA  NA  NA  NA  NA  NA  NA
stat8  NA   NA  NA  NA  NA  NA  NA  NA  NA  NA
stat9  NA   NA  NA  NA  NA  NA  NA  NA  NA  NA
stat10 NA   NA  NA  NA  NA  NA  NA  NA  NA  NA

To reiterate, where there are 0s in df1 and NAs in df2, I would like to keep the 0s. 重申一下,df1中的0和df2中的NAs,我想保持0。 Where there are NAs in both df1 and df2 I would like to keep the NAs. 在df1和df2都有NA的情况下,我想保留NA。 Where there are 0s in df1 and 1s in df2, I would like to keep the 1s. 在df1中有0,在df2中有1s,我想保持1s。

I would appreciate any help with this, as I am a very novice R user! 我很感激任何帮助,因为我是一个非常新手的R用户!

We create a logical matrix and then assign the values to 1 based on the index 我们创建一个逻辑矩阵,然后根据索引将值分配给1

i1 <- (df2 == 1 & !is.na(df2)) & (df1 == 0 & !is.na(df1))
df1[i1] <- 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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