【问题标题】:How can I address the values in a vector based on start and stop indexes from other vectors?如何根据其他向量的开始和停止索引来处理向量中的值?
【发布时间】:2015-08-28 21:41:52
【问题描述】:

假设我有一个全零的向量:

x <- rep(0, 100)

我想将某些范围内的值设置为 1:

starts <- seq(10, 90, 10)
stops <- starts + round(runif(length(starts), 1, 5))

我可以用 for 循环来做到这一点:

for(i in seq_along(starts)) x[starts[i]:stops[i]] <- 1

但我知道这在 R 中是不受欢迎的。我怎样才能以矢量化的方式做到这一点,理想情况下没有外部包?

【问题讨论】:

  • 随机数据的例子,抽奖前最好set.seed

标签: r vector indexing


【解决方案1】:

您可以使用 Map() 获取 所有 索引,Reduce(union, ...) 将该列表下拉到 唯一 索引的原子向量,然后使用 @987654323 @ 或 replace() 替换。

replace(x, Reduce(union, Map(":", starts, stops)), 1L)

或者

x[Reduce(union, Map(":", starts, stops))] <- 1L

此外,for() 循环在 R 中不一定是“皱眉”。这取决于具体情况。很多时候,for() 循环被证明是最有效的路线。

【讨论】:

  • 或者只是unlist(Map(":", starts, stops))。不知道Map,很好的解决方案!
  • 谢谢。你可以这样做。但在重复索引的情况下,您将替换它们两次,效率会降低。
【解决方案2】:

使用apply的解决方案:

x[unlist(apply(cbind(starts, stops), 1, function(x) x[[1]]:x[[2]]))] <- 1

【讨论】:

  • 我认为您需要在索引周围添加一个unlist()
【解决方案3】:
starts <- seq(10, 90, 1)
change_index <- starts[starts %% 10 <= 5]

x[change_index] <- 1

【讨论】:

  • 我的例子被简化了,但是开始和停止是随机的。所以这样的解决方案是行不通的。
  • 你能提供一个更类似于问题的例子吗?
猜你喜欢
  • 2017-01-18
  • 2020-08-24
  • 1970-01-01
  • 1970-01-01
  • 2020-08-19
  • 2019-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多