R split numeric vector at position -


i wondering simple task of splitting vector 2 @ index:

splitat <- function(x, pos){   list(x[1:pos-1], x[pos:length(x)]) }  <- c(1, 2, 2, 3)  > splitat(a, 4) [[1]] [1] 1 2 2  [[2]] [1] 3 

my question: there must existing function this, can't find it? maybe split possibility? naive implementation not work if pos=0 or pos>length(a).

an improvement be:

splitat <- function(x, pos) unname(split(x, cumsum(seq_along(x) %in% pos))) 

which can take vector of positions:

splitat(a, c(2, 4)) # [[1]] # [1] 1 #  # [[2]] # [1] 2 2 #  # [[3]] # [1] 3 

and behave properly (subjective) if pos <= 0 or pos >= length(x) in sense returns whole original vector in single list item. if you'd error out instead, use stopifnot @ top of function.


Comments

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -