insert elements in a vector in R

后端 未结 6 1547
悲哀的现实
悲哀的现实 2020-12-01 16:11

I have a vector in R,

a = c(2,3,4,9,10,2,4,19)

let us say I want to efficiently insert the following vectors, b, and c,

b =         


        
6条回答
  •  爱一瞬间的悲伤
    2020-12-01 16:52

    Here's another function, using Ricardo's syntax, Ferdinand's split and @Arun's interleaving trick from another question:

    ins2 <- function(a,bs,pos){
        as <- split(a,cumsum(seq(a)%in%(pos+1)))
        idx <- order(c(seq_along(as),seq_along(bs)))
        unlist(c(as,bs)[idx])
    }
    

    The advantage is that this should extend to more insertions. However, it may produce weird output when passed invalid arguments, e.g., with any(pos > length(a)) or length(bs)!=length(pos).

    You can change the last line to unname(unlist(... if you don't want a's items named.

提交回复
热议问题