簡體   English   中英

我無法在 R 中保存順序結果的 for 循環?

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

我的for循環算法總是有不同的大小,因為seq輸出不同,因此我無法保存結果。 我怎樣才能做到這一點? 我被卡在循環的mat[?,?]部分,請看下面的例子。 我怎樣才能做到這一點?

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)
  }
    }

另外,你對初始矩陣matnrow有什么建議(這里是15)。

保存輸出將為,對於i<-1k<-1

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

對於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)

等等..

使用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

+-操作是矢量化的,所以你不需要for循環來做到這一點。 使用headtail我們選擇當前值和下一個值的組合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM