[英]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: 如果我有一个向量c(1,2,3,5,7,9,10,12)...和另一个向量c(3,7,10),我将如何产生以下结果:
[[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). 请注意3 7和10如何成为每个列表元素的最后一个数字(最后一个除外)。 Or in a sense the "breakpoint".
或某种意义上的“断点”。 I am sure there is a simple R function I am unknowledgeable of or having loss of memory.
我确定有一个我不了解或内存不足的简单R函数。
Here's one way using cut
and split
: 这是使用
cut
和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
类似于@beginneR的答案,但使用
findInterval
而不是cut
split(x, findInterval(x, y + 1))
# $`0`
# [1] 1 2 3
#
# $`1`
# [1] 5 7
#
# $`2`
# [1] 9 10
#
# $`3`
# [1] 12
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.