Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have 2 vectors, such as these:

A <- c(1,2,NA,NA,NA,NA,7)
B <- c(NA,NA,3,4,NA,NA,7)

I would like to combine them so that the resulting vector is

1,2,3,4,NA,NA,-1

That is

  1. when only 1 value (say X) in either vector at position i exists (the other being NA) the new vector should take the value X at position i.

  2. when both values are NA at position i, the new vector should take the value NA at position i

  3. when both vectors have a value at position i, the new vector should take the value -1 at position i.

I can easily do this with a loop, but it is very slow on a large dataset so can anyone provide a fast way to do this ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

These commands create the vector:

X <- A
X[is.na(A)] <- B[is.na(A)]
X[is.na(B)] <- A[is.na(B)]
X[!is.na(A & B)] <- -1

#[1]  1  2  3  4 NA NA -1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...