简体   繁体   中英

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. How can I do that? I am stuck on the mat[?,?] part of the loop, please look at the example below. 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).

The saving outputs will be, for i<-1 and k<-1

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

for i<-2 and k<-1, k<-2, k<-3 and k<-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 :

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. Using head and tail we select combination of current value and next value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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