R split numeric vector at position

前端 未结 3 2138
不知归路
不知归路 2020-11-27 16:22

I am wondering about the simple task of splitting a vector into two at a certain index:

splitAt <- function(x, pos){
  list(x[1:pos-1], x[pos:length(x)])
         


        
3条回答
  •  心在旅途
    2020-11-27 16:50

    I tried to use flodel's answer, but it was too slow in my case with a very large x (and the function has to be called repeatedly). So I created the following function that is much faster, but also very ugly and doesn't behave properly. In particular, it doesn't check anything and will return buggy results at least for pos >= length(x) or pos <= 0 (you can add those checks yourself if you're unsure about your inputs and not too concerned about speed), and perhaps some other cases as well, so be careful.

    splitAt2 <- function(x, pos) {
        out <- list()
        pos2 <- c(1, pos, length(x)+1)
        for (i in seq_along(pos2[-1])) {
            out[[i]] <- x[pos2[i]:(pos2[i+1]-1)]
        }
        return(out)
    }
    

    However, splitAt2 runs about 20 times faster with an x of length 106:

    library(microbenchmark)
    W <- rnorm(1e6)
    splits <- cumsum(rep(1e5, 9))
    tm <- microbenchmark(
                         splitAt(W, splits),
                         splitAt2(W, splits),
                         times=10)
    tm
    

提交回复
热议问题