Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

r - Splitting vector based on vector of chunk-lengths

I've got a vector of binary numbers. I know the consecutive length of each group of objects; how can I split based on that information (without for loop)?

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

x is the binary number vector that I need to split. .length is the information that I am given. .length essentially tells me that the first group has 2 elements and they are the first two elements 1,0. The second group has 4 elements and contain the 4 numbers that follow the group 1 numbers, 1,0,0,0, etc.

Is there a way of splitting that and returning the splitted item in to a list?

The ugly way is to do with via a for loop keep track of the current cumsum, but I am looking for a more elegant way if there is one.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...