簡體   English   中英

R中的嵌套循環

[英]Nested loops in R

我有一個問題,我確定有一個簡單的解決方案,但我不知道。

背景:我有幾個矩陣,最初是作為列表引入到R中的,但現在它們處於“統一”矩陣中(此格式對於以后的處理是必需的)。 我需要對每一行進行計算(減去向量); 我需要減去一個相同長度的向量。 用於減法的特定向量保存在32個唯一向量的列表中。

統一矩陣內有150個數據幀,其中包含32行(統一矩陣中總共有4800行)。 減矢量的長度為1021,對應於統一矩陣中的相同列數。

dat.y <- rep(1:32, times=150)    
rows <- 32

d.list是32個1D向量的列表,每個向量的長度為1021

mattiff是矩陣4800x1021,以前是尺寸為32x1021的150張tiff圖像

for (i in 1:length(dat.y)
{
for (j in 1:length(rows))
    {
    mattiff2<-mattiff[i, ] - d.list[[j]]    
    }
}

本質上,我想在整個統一矩陣上重復執行32次相減150次的循環。

可重現的示例:

mm <- matrix(100, 128, 1021)
list_sub<-list()

rows<-seq(1, 32, 1)
dat.len<-seq(1, 128, 1)
dat.y<-rep(1:32, times=4)

## random data to substract from mm
for (i in 1:32)
    {
        list_sub[[i]]<-runif(n = 1021, min = 45, max = 80)
    }

## I want this to substract list_sub[[i]] from mm[i,]
## essentially making the loop of 32 rows across all 128
## rows of mm. I.e substracting from mm rows 1...32 with list_sub
## then substracting from mm rows 33...64 with list_sub
## then subtracting from mm rows 65...96 with list_sub
## then subtracting from mm rows 97...128 with list_sub



## I would imagine an approach similar to this would give me the result I want
## to give mm_2: a matrix with the same dimensions of mm
for (i in 1:length(dat.y))
    {
    for (j in 1:length(rows))
        {
            mm_2 <- mm[i,] - list_sub[[j]]
        }
    }

因此,在矩陣mattiff中,有150個32x1021階的矩陣(統一),為4800x1021,並且您想將d.list [[1]]的元素減去到第1,33,65行... ,34,66,... d.list [[2]]的元素,依此類推。
我假設

mattiff2<-mattiff[i, ] - d.list[[j]]

是錯誤的(如可重現的示例),您想要的是mattiff2成為矩陣4800x1021,並減去結果。

這是一種方法:

# arrange the elements of d.list as a matrix 1021x32
d.array <- simplify2array(d.list)
# repeat d.array 150 times for a matrix 1021x4800
sub <- matrix(d.array,1021,4800)
# subtract elementwise
mattiff2 <- mattiff - t(sub)

如果需要,將4800替換為length(dat.y)。

暫無
暫無

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

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