简体   繁体   中英

Creating list of continuous lines from a vector of points

Sorry if this question is vague, I searched and couldn't find an anser. I have some data that looks something like this:

x = c(1,2,3,4,5,6,7,8,9,10)

y = c(T,T,T,F,F,T,T,F,F,T)

I want to join the "TRUE" points as a list of contiguous vectors that I can use for plotting. Ie, a list like this (with a little extra padding):

$`1`
[1] 0.5 3.5

$`2`
[1] 5.5 7.5

$`3`
[1]  9.5 10.5

I know I can do this in a for loop, but I have a LOT of data points and I'm wondering if there is some smart vector operations I can do instead.

An attempt using rle :

ry <- rle(y)
out <- split(x[y], rep(seq_along(ry$values), ry$lengths)[y])

#$`1`
#[1] 1 2 3
#
#$`3`
#[1] 6 7
#
#$`5`
#[1] 10

lapply(out, function(x) range(x) + c(-0.5,0.5))

#$`1`
#[1] 0.5 3.5
#
#$`3`
#[1] 5.5 7.5
# 
#$`5`
#[1]  9.5 10.5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM