Divide the vector into unequal pieces in R

I have the same question as here , except that I want to indicate the length of the split variable with another vector. So something like this:

example.data<-paste("ex",1:10,sep="") example.data [1] "ex1" "ex2" "ex3" "ex4" "ex5" "ex6" "ex7" "ex8" "ex9" "ex10" split.lens <- c(4,2,1,3) 

should provide me with the following list:

 result.list [[1]] [1] "ex1" "ex2" "ex3" "ex4" [[2]] [1] "ex5" "ex6" [[3]] [1] "ex7" [[4]] [1] "ex8" "ex9" "ex10" 

I cannot find a better way to do this with split . Any ideas?

Thanks!

+5
source share
2 answers
 split(example.data, rep(1:4, c(4,2,1,3))) 
+8
source

I added a more general method to the qdapTools dev version to separate the different data types in specific places, Here is an approach:

 ## install qdapTools devtools::install_github("trinker/qdapTools") library(qdapTools) loc_split(example.data, head(cumsum(split.lens) + 1, -1)) ## [[1]] ## [1] "ex1" "ex2" "ex3" "ex4" ## ## [[2]] ## [1] "ex5" "ex6" ## ## [[3]] ## [1] "ex7" ## ## [[4]] ## [1] "ex8" "ex9" "ex10" 

The function essentially wraps code similar to @RStudent when applied to vectors.

+3
source

Source: https://habr.com/ru/post/1208690/


All Articles