Home > Back-end >  Populating an array from a list with a loop in R
Populating an array from a list with a loop in R

Time:09-21

I have a list in R containing values of leaf area by layer by month, like this

ls <- list(month = c(1,1,2,2,3,3,4,4),
           layer = c(0,1,0,1,0,1,0,1),
           LA = c(runif(8)))

I would like to create an array showing a snapshot of the LA by layer for each month, with layer 0 corresponding to the bottom of each matrix in the array, and layer 1 corresponding to the top. I have created an array

canopy <- array(dim = c(2,1,4))

and am trying to populate it with a for loop

for (i in 1:4) {
  if (ls$month == i){
    if (ls$layer == 0){
       canopy[2,1,i] <-  ls$LA
    } else if (ls$layer == 1){
       canopy[1,1,i] <-  ls$LA
    }}}

However, this yields an error

Error in canopy[2, 1, i] <- ls$LA : 
  number of items to replace is not a multiple of replacement length
In addition: Warning messages:
1: In if (ls$month == i) { :
  the condition has length > 1 and only the first element will be used
2: In if (ls$layer == 0) { :
  the condition has length > 1 and only the first element will be used

How can i clean this up?

CodePudding user response:

Putting the data into a 3 dimensional matrix is always tricky. Be sure this is really what you need. For this example a standard matrix/data frame could be a better solution.

In this solution I loop through the number of months and identify the indexes of the vector for each month and then extract those elements out of each vector of the list. One of the tricky parts is layer being 0 or 1. There is no 0 index in R (Python yes) thus I added one to layer to properly place it in the matrix.

Try this:

ls <- list(month = c(1,1,2,2,3,3,4,4),
           layer = c(0,1,0,1,0,1,0,1),
           LA = c(runif(8)))

canopy <- array(dim = c(2,1,4))
#Rows are layer
#Columns are LA
#Matrixes are month

for (i in 1:4) {
  month <- which(ls$month ==i)
  canopy[ls$layer[month] 1, ,i] <-ls$LA[month]
   
}
canopy

, , 1

[,1]
[1,] 0.1941003
[2,] 0.5879553

, , 2

[,1]
[1,] 0.8284857
[2,] 0.7242819

, , 3

[,1]
[1,] 0.8078793
[2,] 0.3489988

, , 4

[,1]
[1,] 0.25424950
[2,] 0.05117571
  • Related