0

I have two vectors : vector1 and vector2 with same length. I would like to get only the value of vector1 where vector1 is not na, and where vector2 is not na. I tried with that code, but it doesn't work :

vector1step1<-ifelse(((is.na(vector1)==F)&(is.na(vector2)==F)), vector1, NA)
vector1step2<-vector1step1[!is.na(vector1step1)]

An idea ? Thank you in advance :)

MrRonsard
  • 1
  • 2

1 Answers1

-2

The best way of thinking about this is probably as a data.frame or matrix, and creating a third vector that results from an apply call to each row. Something like

dta <- data.frame(v1 = vector_step1, v2=vector_step2)
dta$v3 <- apply(dta, 1, function(x) ifelse(!is.na(x[1]), x[1], x[2]))

The 1 in apply means rowwise, slicing out one row at a time. The first element in each slice, temporarily renamed x[1], will be from v1, the second, temporarily renamed x[2] will be from the same row, but v2.

You could also extend the code in apply to deal with cases where both v1 and v2 are NA, by nesting in another ifelse statement.

JonMinton
  • 1,239
  • 2
  • 8
  • 26
  • 1
    No, `apply` is not the best way here. There is no reason to loop over the rows. Also, don't use `ifelse` for length-1 vectors. Use `if` and `else` in such a case. – Roland Apr 30 '15 at 13:45