【问题标题】:Vectorize this for loop: applying a function to sub-indices?将此 for 循环向量化:将函数应用于子索引?
【发布时间】:2011-03-15 23:43:09
【问题描述】:

有什么方法可以矢量化以下内容吗?

# x: some vector
# index: some vector of indeces
n <- length(index)
y <- rep(NA, n)
for (i in 1:n) {
  y[i] = myfunction(x[1:index[i])
}

基本上,我想将myfunction 应用于向量x 的各个子集。似乎 apply 函数不是用来处理这个问题的。

【问题讨论】:

    标签: r vectorization


    【解决方案1】:

    我不确定我是否理解你在做什么,但如果你想从x 向量中获取第一个index-es 元素数量,而不是组成一些示例数据:

    x <- runif(10)
    index <- c(2,5,4,8)
    

    然后尝试:

    > lapply(index, function(index) return(x[1:index]))
    [[1]]
    [1] 0.3869757 0.4060021
    
    [[2]]
    [1] 0.3869757 0.4060021 0.4843015 0.2064443 0.4614179
    
    [[3]]
    [1] 0.3869757 0.4060021 0.4843015 0.2064443
    
    [[4]]
    [1] 0.3869757 0.4060021 0.4843015 0.2064443 0.4614179 0.9278044 0.7351291
    [8] 0.9792204
    

    【讨论】:

      猜你喜欢
      • 2020-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      • 1970-01-01
      相关资源
      最近更新 更多