2016-05-11 14 views
0

zusammengeführt werden Ich habe eine Matrix namens mymat. Ich möchte die Spalte und value2 zusammenführen, wo der eine Werte hat und der andere hat NAs und erstellen Sie eine einzelne Spalte damit alle NAs entfernen und erhalten Sie die result.Wie zwei Spalten mit alternierenden NAs in R

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"))) 

Ergebnis

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" 
+0

@Symbolix Sorry, dass war eine Matrix. – MAPK

Antwort

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

Mit richtigen for und Konditionaloperator if, else Sie den Wunsch, Datenrahmen wie erhalten:

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 
2

Sie können versuchen,

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" 

oder äquivalent

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