Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining two vectors element-by-element

Tags:

r

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 ?

like image 704
Robert Long Avatar asked Sep 20 '12 11:09

Robert Long


People also ask

How do you combine vector elements?

Vectors can be combined via the function c. For examples, the following two vectors n and s are combined into a new vector containing elements from both vectors.

How do you combine vectors in C++?

Given two vectors, join these two vectors using STL in C++. Approach: Joining can be done with the help of set_union() function provided in STL. Syntax: set_union (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result);

How do I combine values into vectors in R?

To concatenate a vector or multiple vectors in R use c() function. This c() function is used to combine the objects by taking two or multiple vectors as input and returning the vector with the combined elements from all vectors.

What effect does concatenate function has on vectors?

Concatenate function: This method combines the arguments and results in a vector. All the arguments are converted to a common type that is the return value type. This function is also used to convert the array into vectors.


1 Answers

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
like image 134
Sven Hohenstein Avatar answered Sep 21 '22 05:09

Sven Hohenstein