简体   繁体   中英

Nested loops in R

I've got a problem that I'm sure has a simple solution but I can't figure it out.

Background: I've got several matrices which I have brought in to R, initially as a list but now they are in a "unified" matrix (this format is required for later processing). I need to perform a calculation on every row (subtracting a vector); I need to substract a vector of the same length. The specific vector for substraction is held in a list of 32 unique vectors.

Within the unified matrix are 150 data frames which have 32 rows (giving a total of 4800 rows in the unified matrix). The subtraction vector is 1021 in length, which corresponds to the same amount of columns in the unified matrix.

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

d.list is a list of 32 1D vectors each 1021 in length

mattiff is a matrix 4800x1021 which was previously 150 tiff images of dimensions 32x1021

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

Essentially, I want to repeat a loop of the substraction of 32 rows 150 times across the unified matrix.

Reproducable example:

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

So you have 150 matrices of order 32x1021 unified (rbinded) in a matrix mattiff which is 4800x1021 and you want to subtract to rows 1,33,65,... the elements of d.list[[1]], to rows 2,34,66,... the elemnts of d.list[[2]] and so on..
I am assuming

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

is wrong (as is the reproducible example) and what you want is mattiff2 to be a matrix 4800x1021 with the resulting subtractions.

Here is a way:

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

Substitute 4800 with length(dat.y) if needed.

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