简体   繁体   English

我无法在 R 中保存顺序结果的 for 循环?

[英]I can not save the for loop of the sequential results in R?

My for loop algorithm has always different sizes, because of the different outputs of the seq , for that reason, I can't save the results.我的for循环算法总是有不同的大小,因为seq输出不同,因此我无法保存结果。 How can I do that?我怎样才能做到这一点? I am stuck on the mat[?,?] part of the loop, please look at the example below.我被卡在循环的mat[?,?]部分,请看下面的例子。 How can I do that?我怎样才能做到这一点?

d<-data.frame(L1=c(1,6,8), L2=c(3,14,22))
    mat<-matrix(c(0),15,2)

for (i in 1:nrow(d)) {
    x1<-seq(d$L1[i],d$L2[i],2)
    x1
    for (k in seq_along(x1[-1])) {
      
      L1<- x1[k]
      L2<- x1[k+1]
      mat[?,]<- c(L1+L2,L1-L2)
  }
    }

In addition, what do you recommend for the nrow of the initial matrix mat (it is 15 here).另外,你对初始矩阵matnrow有什么建议(这里是15)。

The saving outputs will be, for i<-1 and k<-1保存输出将为,对于i<-1k<-1

mat[1,]<-c(4,-2),

for i<-2 and k<-1, k<-2, k<-3 and k<-4对于i<-2k<-1, k<-2, k<-3k<-4

 mat[2,]<-c(14,-2), mat[3,]<-c(18,-2),mat[4,]<-c(22 ,-2) and mat[5,]<-c(22 ,-2)

and so on..等等..

Try this approach using apply which will :使用apply尝试这种方法,它将:

do.call(rbind, apply(d, 1, function(x) {
  x1 <- seq(x[1], x[2], 2)
  cbind(head(x1, -1) + tail(x1, -1), head(x1, -1) - tail(x1, -1))
}))

#      [,1] [,2]
# [1,]    4   -2
# [2,]   14   -2
# [3,]   18   -2
# [4,]   22   -2
# [5,]   26   -2
# [6,]   18   -2
# [7,]   22   -2
# [8,]   26   -2
# [9,]   30   -2
#[10,]   34   -2
#[11,]   38   -2
#[12,]   42   -2

+ and - operations are vectorised so you don't need a for loop to do that. +-操作是矢量化的,所以你不需要for循环来做到这一点。 Using head and tail we select combination of current value and next value.使用headtail我们选择当前值和下一个值的组合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM