[英]Replace values between two data frames in R
I am trying to solve a little question related to two dataframes in R. I have two data frames D1
and D2
: 我试图解决与R中的两个数据帧相关的一个小问题。我有两个数据帧
D1
和D2
:
D1
ID I1 I2 I3
1 001 1 2 9
2 002 3 5 9
3 003 8 7 9
D2
ID I1 I2 I3
1 001 NA 1 NA
2 002 1 1 NA
3 003 NA NA 1
These dataframes are produced with the next code: 这些数据帧是使用下一个代码生成的:
D1=data.frame(ID=c("001","002","003"),I1=c(1,3,8),I2=c(2,5,7),I3=c(9,9,9),stringsAsFactors=FALSE)
D2=data.frame(ID=c("001","002","003"),I1=c(NA,1,NA),I2=c(1,1,NA),I3=c(NA,NA,1),stringsAsFactors=FALSE)
The dataframe D2
has rows with NA
and non NA
values. 数据帧
D2
具有NA
和非NA
值的行。 So I want to replace the non NA
values in D2
with their respective value in D1
. 所以我想,以取代非
NA
中值D2
与各自价值D1
。 For example in the first row of D2
the second column in non NA
, so this value should be replaced with 2
from D2
. 例如,在
D2
的第一行中,非NA
的第二列,因此该值应该用来自D2
2
替换。 I tried building a matrix with the non NA
values in D2
by using this code: 我尝试使用以下代码在
D2
构建一个非NA
值的矩阵:
mm=!is.na(D2[-1])
I1 I2 I3
[1,] FALSE TRUE FALSE
[2,] TRUE TRUE FALSE
[3,] FALSE FALSE TRUE
But when I trid to replace with a code like this D1[mm]
I don't get the expected result. 但是,当我试图用这样的代码替换
D1[mm]
我没有得到预期的结果。 I would like to get something like this: 我想得到这样的东西:
ID I1 I2 I3
1 001 NA 2 NA
2 002 3 5 NA
3 003 NA NA 9
Thanks! 谢谢!
Try the following: 请尝试以下方法:
D2[!is.na(D2)] <- D1[!is.na(D2)]
D2
ID I1 I2 I3
1 001 <NA> 2 <NA>
2 002 3 5 <NA>
3 003 <NA> <NA> 9
@DatamineR's solution is the first one I thought of as well, but it has the unfortunate effect of indexing the data.frames as vectors, which promotes the atomic type to character (due to the ID column), which you may not want. @ DatamineR的解决方案也是我想到的第一个解决方案,但它将data.frames索引为向量具有不幸的效果,它将原子类型提升为字符(由于ID列),这可能是您不想要的。
Here's an alternative that preserves the numericness of the I1-3 columns: 这是保留I1-3列数字性的替代方法:
aggregate(.~ID,rbind(D1,D2),function(a) if (is.na(a[2])) NA else a[1],na.action=na.pass);
## ID I1 I2 I3
## 1 001 NA 2 NA
## 2 002 3 5 NA
## 3 003 NA NA 9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.