如何在R中将两列与交替的NA合并

时间:2016-05-11 00:24:39

标签: r

我有一个名为mymat的矩阵。我想合并列value1value2,其中一列有值,另一列有NAs并创建一个列,从而删除所有NA并获取result

mymat<-structure(c(NA, "0.00802", NA, NA, NA, "0.00776", NA, "-0.0218", 
"0.00212", "0.369", "AOGC-05-0009:AOGC-03-0122", "AOGC-08-0006:AOGC-03-0122", 
"AOGC-08-0032:AOGC-03-0122", "AOGC-08-0054:AOGC-03-0122", "AOGC-08-0083:AOGC-03-0122"
), .Dim = c(5L, 3L), .Dimnames = list(c("1", "2", "3", "4", "5"
), c("value1", "value2", "samples"))) 

结果

value.wanted    samples                    
"0.00776" "AOGC-05-0009:AOGC-03-0122"
"0.00802" "AOGC-08-0006:AOGC-03-0122"
"-0.0218" "AOGC-08-0032:AOGC-03-0122"
"0.00212" "AOGC-08-0054:AOGC-03-0122"
"0.369"   "AOGC-08-0083:AOGC-03-0122"

3 个答案:

答案 0 :(得分:4)

merge.columns <- ifelse(is.na(mymat[,1]),mymat[,2],mymat[,1])

答案 1 :(得分:2)

你可以尝试

cbind(value.wanted=t(mymat[,1:2])[!is.na(t(mymat[,1:2]))], samples=mymat[,3])
#  value.wanted samples                     
#1 "0.00776"    "AOGC-05-0009:AOGC-03-0122"
#2 "0.00802"    "AOGC-08-0006:AOGC-03-0122"
#3 "-0.0218"    "AOGC-08-0032:AOGC-03-0122"
#4 "0.00212"    "AOGC-08-0054:AOGC-03-0122"
#5 "0.369"      "AOGC-08-0083:AOGC-03-0122"

或者,相当于

cbind(value.wanted=na.omit(c(t(mymat[,1:2]))), samples=mymat[,3])

答案 2 :(得分:0)

使用正确的for和条件运算符ifelse,您将获得所需的数据框:

value.wanted <- c()
for(i in 1:nrow(mymat)) {
  if (!is.na(mymat[i, 1])) {
    value.wanted <- c(value.wanted, mymat[i, 1])
  } else {
    value.wanted <- c(value.wanted, mymat[i, 2])
  }
}

df <- data.frame(value.wanted, mymat[, 3])

names(df) <- c("value.wanted", "samples")
df # print the result