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
285 views
in Technique[技术] by (71.8m points)

r - Add a series of elements in different locations within a vector

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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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


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

...