在R中将矢量拆分为不相等的块

时间:2021-12-09 02:25:29

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!

2 个解决方案

#1


9  

split(example.data, rep(1:4, c(4,2,1,3)))

#2


3  

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:

我在qdapTools的dev版本中添加了一种更通用的方法,以便在特定位置拆分各种数据类型。这是方法:

## 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.

当应用于向量时,该函数实际上包含类似于@ RStudent的答案的代码。

#1


9  

split(example.data, rep(1:4, c(4,2,1,3)))

#2


3  

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:

我在qdapTools的dev版本中添加了一种更通用的方法,以便在特定位置拆分各种数据类型。这是方法:

## 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.

当应用于向量时,该函数实际上包含类似于@ RStudent的答案的代码。