Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a series of elements in different locations within a vector

Tags:

r

I aim to insert multiple elements to a vector each in different locations. This is the example followed by a number of trials which do not work.

w  <- c( 1,3,2,4,2,3,2,4,5,7,9,3,2,4,2,5,7,4,2 )
u  <- c( 3,7,9,12 )
o  <- c( 10 , 20 , 30 , 40 )

I have tried:

append ( w , o , after = u )  

# which adds the series one time in the first location of after 

fun <- function (x) append ( w , o[[x]] , after = u[[x]] )
lapply ( seq ( length ( u )) , fun )

# which adds one element to the list each time for a new vector producing a  number of vectors 

for (i in length(o)) {
append ( w , o[[i]] , after = u[[i]] )
}
# which basically does nothing

Desired Output

1,3,2,10,4,2,3,2,20,4,5,30,7,9,3,40,2,4,2,5,7,4,2

Is there a way to insert each element one at a time in each specific location? I have seen several questions addressing the append basic for a single element with one location or two elements to be added to the same position however not multiple elements to be added to multiple locations in a vector.

like image 403
Barnaby Avatar asked Mar 19 '16 18:03

Barnaby


People also ask

How do you add all elements to a vector?

Sum up of all elements of a C++ vector can be very easily done by std::accumulate method. It is defined in <numeric> header. It accumulates all the values present specified in the vector to the specified sum.

How do I add multiple values to a vector in R?

To append multiple elements to a Vector in R, use the append() method and pass the vector to the existing vector. It will spread out in the existing vector and add multiple elements to that vector.


2 Answers

Here's another vectorized way to do this

New <- rep(w, (1:2)[(1:length(w) %in% u) + 1])
New[u + 1:length(u)] <- o
New
# [1]  1  3  2 10  4  2  3  2 20  4  5 30  7  9  3 40  2  4  2  5  7  4  2

This is basically works on subsetting vectors technique, by extracting the values in u twice and the reassigning them with values from o

like image 101
David Arenburg Avatar answered Sep 21 '22 22:09

David Arenburg


x <- numeric(length(w)+length(o))
ind <- u + order(u) #index to insert o vector (which I shamelessly borrowed from Josilber's answer)
x[ind] <- o
x[-ind] <- w
x
# [1]  1  3  2 10  4  2  3  2 20  4  5 30  7  9  3 40  2  4  2  5  7  4  2
like image 21
Khashaa Avatar answered Sep 19 '22 22:09

Khashaa