【问题标题】:partition sequence by barriers of indices按索引障碍划分序列
【发布时间】:2020-03-14 16:53:12
【问题描述】:

给定一个序列s <- 10:1base R 中是否有任何优雅的函数允许您为s 的索引设置障碍以划分s

例如,如果barriers <- c(3,7),表示分离发生在s的第3和第7位,这样期望的输出应该是一个分区列表,比如

> list(10:8,7:4,3:1)
[[1]]
[1] 10  9  8

[[2]]
[1] 7 6 5 4

[[3]]
[1] 3 2 1

请注意,如果barriers <- c(3,10),由于第 10 位屏障之外的分区没有任何剩余,因此所需的输出应为

> list(10:8,7:1)
[[1]]
[1] 10  9  8

[[2]]
[1] 7 6 5 4 3 2 1

解决方案:感谢@RonakShah 和@GKi 提供的线索

split(s, findInterval(seq_along(s), barriers, left.open = TRUE))

【问题讨论】:

  • 您可以使用split(s, findInterval(s, barriers + 1)),但我不明白您的第二个条件。
  • @RonakShah 感谢您的回答!第二个条件是,最后一个屏障,即barrier <- c(3,10)中的10,位于序列的最后位置,这样s只有2个分区,10个条目。
  • @RonakShah 我猜split(s, findInterval(seq_along(s), barriers+1)) 正是我需要保持与s 相同顺序的东西。再次感谢您!

标签: r arrays partition


【解决方案1】:

您可以使用splitfindInterval 喜欢:

s <- 10:1
barriers <- c(3,7)
split(s, findInterval(seq_along(s), barriers, left.open = TRUE))
#$`0`
#[1] 10  9  8
#
#$`1`
#[1] 7 6 5 4
#
#$`2`
#[1] 3 2 1

barriers <- c(3,10)
split(s, findInterval(seq_along(s), barriers, left.open = TRUE))
#$`0`
#[1] 10  9  8
#
#$`1`
#[1] 7 6 5 4 3 2 1

【讨论】:

  • 感谢您的回答!我想split(s, findInterval(seq_along(s), barriers+1)) 正是我需要保持与s 相同顺序的东西。
  • @ThomasIsCoding 我觉得它更像split(s, findInterval(s, barriers, left.open = TRUE))
  • 是的,正是:)
  • @ThomasIsCoding 或者-的解决方案?
  • 我认为split(s, findInterval(seq_along(s), barriers, left.open = TRUE)) 很适合我的目标,因为障碍是针对索引而不是s,所以- 的方法可能不适用于我的其他一般情况。例如,barrier &lt;- c(3,10) 无法达到预期的输出
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-03
  • 2013-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-15
相关资源
最近更新 更多