Nematode - 10 days ago 7

R Question

I know this is a very basic question, but I can't seem to find a direct answer anywhere. My real code is performing some calculations on a list of spatial polygon data frames, then slotting the metrics calculated into a pre-allocated matrix. My problem is that when I call the matrix after the loop again, it's still empty. I've created toy code that maintains this issue.

`#create the columns to be filled`

empty<-matrix(,nrow=4,ncol=3)

colnames(empty)<-c("NF", "PF", "AA")

lapply(1:4, function(x){

NF<-2

#Proportion of forest

PF<- 4

#Average fragment area

AA<- 6

#plug them into my awaiting columns

empty[x,]<-c(NF, PF, AA)

})

head(empty)

returns

`NF PF AA`

[1,] NA NA NA

[2,] NA NA NA

[3,] NA NA NA

[4,] NA NA NA

Answer

The problem is that you fill in the matrix within `lapply`

which does not work. You could do instead:

```
l <- lapply(1:4, function(x){
NF<-2
PF<- 4
AA<- 6
c(NF, PF, AA)
})
m <- matrix(unlist(l), ncol = 3, byrow = T)
colnames(m) <- c("NF", "PF", "AA")
# NF PF AA
#[1,] 2 4 6
#[2,] 2 4 6
#[3,] 2 4 6
#[4,] 2 4 6
```

Its more efficient as you do not grow the matrix within a loop.