![](/img/trans.png)
[英]R Split a List into unequal chunks, with chunk size given by another vector
[英]Split a vector into unequal chunks in R
我有同样的问题在这里 ,我除了要指定另一个向量变量分裂长度。 所以,像这样:
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)
应该给我以下列表:
result.list
[[1]]
[1] "ex1" "ex2" "ex3" "ex4"
[[2]]
[1] "ex5" "ex6"
[[3]]
[1] "ex7"
[[4]]
[1] "ex8" "ex9" "ex10"
我无法找出split
的最佳方法。 有任何想法吗?
谢谢!
split(example.data, rep(1:4, c(4,2,1,3)))
我在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"
当应用于向量时,该函数实质上包含类似于@ RStudent答案的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.