Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a vector into unequal chunks in R

Tags:

split

r

I have the same question as here, except I want to specify the variable split lengths 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 give me the following list:

result.list
[[1]]
[1] "ex1" "ex2" "ex3" "ex4"

[[2]]
[1] "ex5" "ex6"

[[3]]
[1] "ex7"

[[4]]
[1] "ex8"  "ex9"  "ex10"

I can't figure out the best way to do this with split. Any ideas?

Thanks!

like image 884
Plastic Soul Avatar asked Dec 09 '14 20:12

Plastic Soul


2 Answers

split(example.data, rep(1:4, c(4,2,1,3)))
like image 164
DatamineR Avatar answered Sep 28 '22 07:09

DatamineR


I have added a more general method to the dev version of qdapTools to split various data types at specific locations. Here is that 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's answer when applied to vectors.

like image 37
Tyler Rinker Avatar answered Sep 28 '22 09:09

Tyler Rinker