insert elements in a vector in R

后端 未结 6 1542
悲哀的现实
悲哀的现实 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:42

    You can use the following function,

    ins(a, list(b, d), pos=c(3, 7))
    # [1]  2  3  4  2  1  9 10  2  4  0  1  4 19
    

    where:

    ins <- function(a, to.insert=list(), pos=c()) {
    
      c(a[seq(pos[1])], 
        to.insert[[1]], 
        a[seq(pos[1]+1, pos[2])], 
        to.insert[[2]], 
        a[seq(pos[2], length(a))]
        )
    }
    

提交回复
热议问题