2017-03-02 46 views
0

我有以下矩陣:刪除NA和COLAPSE列成一列,R

 V1 V2 V3 V4 V4 
[1,] "a" "j" "d" "e" NA   
[2,] "a" "b" "d" "e" NA   
[3,] "a" "j" "g" "f" NA   
[4,] "a" "g" "f" NA NA 

我想:

V1 V2 
[1,] "ajde"    
[2,] "abde"    
[3,] "ajgf"   
[4,] "agf" 

我知道如何使用矩陣減少至一個列matrix(do.call(paste0, as.data.frame(M)))以及如何使用m[!is.na(m[i,])]按行刪除NA。我只是不知道該怎麼做,只是兩個在一起,因爲任何時候我試圖在整個矩陣上使用m [!is.na(m)],我最終得到一個大行

回答

2

我們可以使用使用gsub除去NA

V1 <- gsub("NA+", "", do.call(paste0, as.data.frame(M))) 
V1 
#[1] "ajde" "abde" "ajgf" "agf" 

matrix(V1, ncol=1) 

或者,我們可以使用傳統的方法與apply

apply(M, 1, function(x) paste(x[!is.na(x)], collapse=""))