R:将数据框中的值替换为作为占位符的NA

时间:2012-07-25 21:38:44

标签: r dataframe

我希望在第一个数据帧中存在一个值的情况下,用另一个数据帧中的值替换一个数据帧中的值。

第一个数据框由1或0的值组成,NA为占位符。

a <- structure(list(A.1 = c(1L, 0L, NA, 1L, 1L, 0L), A.2 = c(1L, 1L, 
1L, NA, 1L, NA), A.3 = c(0L, NA, NA, 0L, NA, NA), A.4 = c(NA, 
1L, 1L, NA, 0L, NA), A.5 = c(NA, NA, 1L, NA, NA, NA), A.6 = c(NA, 
NA, 1L, NA, NA, 1L)), .Names = c("A.1", "A.2", "A.3", "A.4", 
"A.5", "A.6"), class = "data.frame", row.names = c(NA, -6L))

第二个数据帧包含应该替换第一个数据帧中的NA位置的1或0的值

r <- structure(list(R.1 = c(45L, 33L, 44L, 24L, 32L, 22L), R.2 = c(33L, 
99L, 44L, 25L, 25L, 33L), R.3 = c(22L, 77L, 22L, NA, 26L, NA), 
    R.4 = c(NA, NA, 32L, NA, NA, NA)), .Names = c("R.1", "R.2", 
"R.3", "R.4"), class = "data.frame", row.names = c(NA, -6L))

目标是:

d <- structure(list(D.1 = c(45L, 33L, NA, 24L, 32L, 22L), D.2 = c(33L, 
99L, 44L, NA, 25L, NA), D.3 = c(22L, NA, NA, 25L, NA, NA), D.4 = c(NA, 
77L, 44L, NA, 26L, NA), D.5 = c(NA, NA, 22L, NA, NA, NA), D.6 = c(NA, 
NA, 32L, NA, NA, 33L)), .Names = c("D.1", "D.2", "D.3", "D.4", 
"D.5", "D.6"), class = "data.frame", row.names = c(NA, -6L))

任何&amp;欢迎所有建议。

2 个答案:

答案 0 :(得分:6)

d <- t(a)
d[!is.na(d)] <- t(r)[!is.na(t(r))]
t(d)
     A.1 A.2 A.3 A.4 A.5 A.6
[1,]  45  33  22  NA  NA  NA
[2,]  33  99  NA  77  NA  NA
[3,]  NA  44  NA  44  22  32
[4,]  24  NA  25  NA  NA  NA
[5,]  32  25  NA  26  NA  NA
[6,]  22  NA  NA  NA  NA  33

另外,请注意t()返回矩阵而不是data.frame

答案 1 :(得分:3)

d <- matrix(data=NA, ncol=ncol(a),nrow=nrow(a)) # Initialize matrix

replacements <- t(r) # Transpose R for na.omit()

# Replace
for (x in 1:nrow(a)) { 
  locations <- which(!is.na(a[x,]))
  d[x,locations] <- na.omit(replacements[,x])
  }