Splitting vector based on vector of chunk-lengths

断了今生、忘了曾经 提交于 2019-11-29 10:24:41

You can use rep to set up the split-by variable, the use split

x = c("1","0","1","0","0","0","0","0","1")
.length = c(group1 = 2,group2=4, group3=3)

split(x, rep.int(seq_along(.length), .length))
# $`1`
# [1] "1" "0"
#
# $`2`
# [1] "1" "0" "0" "0"
#
# $`3`
# [1] "0" "0" "1"

If you wanted to take the group names with you to the split list, you can change rep to replicate the names

split(x, rep.int(names(.length), .length))
# $group1
# [1] "1" "0"
#
# $group2
# [1] "1" "0" "0" "0"
#
# $group3
# [1] "0" "0" "1"

Another option is

split(x,cumsum(sequence(.length)==1))
#$`1`
#[1] "1" "0"

#$`2`
#[1] "1" "0" "0" "0"

#$`3`
#[1] "0" "0" "1"

to get the group names

split(x, sub('.$', '', names(sequence(.length))))
#$group1
#[1] "1" "0"

#$group2
#[1] "1" "0" "0" "0"

#$group3
#[1] "0" "0" "1"
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!