Home > Mobile >  An efficient way to expand R vector
An efficient way to expand R vector

Time:03-06

In R, I have a vector of indices (A) and values (B). What is an efficient (preferably parallel) approach in R to expand A and B to C, where C is the values in B located in the index of A?

Example:

A = c(4, 7, 11, 20)

B = c(11, 14, 22, 3)

C = c(0,0,0,11,0,0,14,0,0,0,22,0,0,0,0,0,0,0,0,3)

The Brute-force approach is a for-loop which is not what I am looking for.

CodePudding user response:

Here is one way -

vec <- numeric(max(A))
vec[A] <- B
vec
#[1]  0  0  0 11  0  0 14  0  0  0 22  0  0  0  0  0  0  0  0  3

where vec <- numeric(max(A)) initialises a numeric vector of length max(A) which in this example is 20.

  •  Tags:  
  • r
  • Related