绕过for循环R中的聚合

绕过for循环R中的聚合,r,for-loop,R,For Loop,我想找到数组的第一个索引k,其中k大于给定截止点之前的聚合。代码中如下所示: k <- 0 agg <- 0 while (agg < cutoff) { k <- k +1 agg <- sum(array[1:k]) } k您可以使用以下选项: seed(123)#in order to have reproducible "random" numbers m1 <- matrix(sample(10),nrow

我想找到数组的第一个索引k,其中k大于给定截止点之前的聚合。代码中如下所示:

k   <- 0
agg <- 0
while (agg < cutoff) {   
  k <- k +1
  agg <- sum(array[1:k]) 
}

k您可以使用以下选项:

seed(123)#in order to have reproducible "random" numbers
m1 <- matrix(sample(10),nrow = 5,ncol = 2)# create a matrix

 m1
       [,1] [,2]
  [1,]    7    5
  [2,]    4    2
  [3,]    9    8
  [4,]    1    6
  [5,]    3   10    

cutoff <- 5 #applying cutoff value
apply(m1,2,function(x){x<cutoff})#checking each column using apply instead of loop
seed(123)#以获得可复制的“随机”数字

m1首先我们找到部分和的数组:

x <- 1:10
partial_sums <- Reduce('+', x, accumulate = T)
partial_sums
[1] 六,


请注意,
索引
可能为空。

请注意,您还需要添加一部分数据。否,我想检查索引之前的合计是否大于截止值。您能否在给定
m1
的情况下编写您想象的输出?
cutoff<-30# a new cutoff
v1<-unlist(lapply(seq_along(1:(nrow(m1)*ncol(m1))),function(x){sum(m1[1:x])}))#adding the values of each cell 
which(v1>=cutoff)[1]#find the 1st of occurrence
x <- 1:10
partial_sums <- Reduce('+', x, accumulate = T)
partial_sums
cutoff <- 17
indices <- which(partial_sums > cutoff)
indices[1]