I'm having difficulty populating a matrix within an lapply loop.
In my data, I have a list of 135 geospatial points. Within the lapply loop, I am calculating various metrics based on the landscape within 3 different radii from these site coordinates. What I would like to do is cycle through each combination of 135 sites and 3 radii, then populate each row of my blank, pre-prepared matrix with the (site,radius,metric1,metric2,metric3).
I have created a simple script that replicates the issue I'm running into. If it is possible for me to apply the do.call(rbind, absdf)
command as in here then I have not yet figured out how...
# Generate empty matrix:
mymatrix <- matrix(,nrow=18, ncol=5)
# A vector with length of x (in my data this is the list of 135 sites):
a <- 1:6
#These sets will represent my metrics
b <- rnorm(6, 5, 10)
c <- rnorm(6, 100, 20)
d <- rnorm(6, 20, 20)
# Radius vector:
rad <- c(100,200,300)
# The loop: lapply for site within lapply for radius
lapply(1:3,function(r){
lapply(1:6,function(x){
row.number <- (r-1)*6+x
tmpvector <- c(a[x], b[x], c[x], d[x], rad[r])
mymatrix[row.number,] <- tmpvector
})
})
View(mymatrix)
With the code as now written, the resulting matrix is still blank.
If I write this simple example as a for loop
mymatrix <- matrix(,nrow=18, ncol=5)
a <- 1:6
b <- rnorm(6, 5, 10)
c <- rnorm(6, 100, 20)
d <- rnorm(6, 20, 20)
rad <- c(100,200,300)
for (r in 1:3) {
for (x in 1:6) {
row.number <- (r-1)*6+x
tmpvector <- c(a[x], b[x], c[x], d[x], rad[r])
mymatrix[row.number,] <- tmpvector
}
}
View(mymatrix)
then the matrix fills with values as I expect. I apologise if I am making a simple blunder: I am very new to these loops!
NB I would also be open to creating a continuous list of this data, which I could then transform into a more useful format!