3

I have for example vectors like the following:

 a= c(1, NA, NA, 2, 3)
 b=c(NA, 1, NA, NA, NA)
 c=c(NA, NA, 5, NA, NA)

I wish to merge the three vectors to get

  d=c(1,1,5,2,3)

Is there a way of doing this without extensive looping? Many thanks :)

akrun
  • 874,273
  • 37
  • 540
  • 662
Coldfusion
  • 163
  • 1
  • 1
  • 4

2 Answers2

3

You could try

 rowSums(cbind(a,b,c), na.rm=TRUE)
 #[1] 1 1 5 2 3

or

mat <- cbind(a,b,c)
mat[cbind(1:nrow(mat),max.col(!is.na(mat)))]
#[1] 1 1 5 2 3

Or

ind <- which(!is.na(mat), arr.ind=TRUE)
mat[ind[order(ind[,1]),]]
#[1] 1 1 5 2 3
akrun
  • 874,273
  • 37
  • 540
  • 662
3

I would consider pmin or pmax for a more direct approach given the conditions you describe:

pmin(a, b, c, na.rm = TRUE)
# [1] 1 1 5 2 3
pmax(a, b, c, na.rm = TRUE)
# [1] 1 1 5 2 3
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
  • @akrun, thanks. I think your approach would still be faster though--I think that `rowSums` is pretty heavily optimized. Oh, and congrats on becoming Legendary! :-) – A5C1D2H2I1M1N2O1R2T1 Mar 31 '15 at 17:02