insert elements in a vector in R

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

    Try this:

    result <- vector("list",5)
    result[c(TRUE,FALSE)] <- split(a, cumsum(seq_along(a) %in% (c(3,7)+1)))
    result[c(FALSE,TRUE)] <- list(b,d)
    f <- unlist(result)
    
    identical(f, e)
    #[1] TRUE
    

    EDIT: generalization to arbitrary number of insertions is straightforward:

    insert.at <- function(a, pos, ...){
        dots <- list(...)
        stopifnot(length(dots)==length(pos))
        result <- vector("list",2*length(pos)+1)
        result[c(TRUE,FALSE)] <- split(a, cumsum(seq_along(a) %in% (pos+1)))
        result[c(FALSE,TRUE)] <- dots
        unlist(result)
    }
    
    
    > insert.at(a, c(3,7), b, d)
     [1]  2  3  4  2  1  9 10  2  4  0  1 19
    
    > insert.at(1:10, c(4,7,9), 11, 12, 13)
     [1]  1  2  3  4 11  5  6  7 12  8  9 13 10
    
    > insert.at(1:10, c(4,7,9), 11, 12)
    Error: length(dots) == length(pos) is not TRUE
    

    Note the bonus error checking if the number of positions and insertions do not match.

提交回复
热议问题