0

I have the following matrix:

      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 

I want to get:

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

I know how to reduce a matrix to one column by using matrix(do.call(paste0, as.data.frame(M))) and how to remove the NA by row using m[!is.na(m[i,])]. I just do not know how to but the two together as any time I try to use m[!is.na(m)] on the whole matrix, I end up with one large row

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
ushham
  • 185
  • 1
  • 7

1 Answers1

2

We can use use gsub to remove the NA

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

matrix(V1, ncol=1)

Or we can use the traditional approach with apply

apply(M, 1, function(x) paste(x[!is.na(x)], collapse=""))
akrun
  • 874,273
  • 37
  • 540
  • 662