简体   繁体   中英

Splitting numeric vectors in R

If I have a vector, c(1,2,3,5,7,9,10,12)...and another vector c(3,7,10), how would I produce the following:

[[1]]
1,2,3

[[2]]
5,7

[[3]]
9,10

[[4]]
12

Notice how 3 7 and 10 become the last number of each list element (except the last one). Or in a sense the "breakpoint". I am sure there is a simple R function I am unknowledgeable of or having loss of memory.

Here's one way using cut and split :

split(x, cut(x, c(-Inf, y, Inf)))
#$`(-Inf,3]`
#[1] 1 2 3
#
#$`(3,7]`
#[1] 5 7
#
#$`(7,10]`
#[1]  9 10
#
#$`(10, Inf]`
#[1] 12

Could do

split(x, cut(x, unique(c(y, range(x)))))

## $`[1,3]`
## [1] 1 2 3

## $`(3,7]`
## [1] 5 7

## $`(7,10]`
## [1]  9 10

## $`(10,12]`
## [1] 12

Similar to @beginneR 's answer, but using findInterval instead of cut

split(x, findInterval(x, y + 1))
# $`0`
# [1] 1 2 3
# 
# $`1`
# [1] 5 7
# 
# $`2`
# [1]  9 10
# 
# $`3`
# [1] 12

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