Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

r - Combining two vectors element-by-element

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...