Search code examples
rdataframeloopsraster

Looping dataframe values into a raster through time


I have a raster N showing the overall distribution of a species. The raster cells have a value of 1 where the species is present, and a value of 0 otherwise. I also have a data frame DF showing the relative biomass of this same species over time:

Biomass<-c(0.9, 1.2, 1.3)
Year<-c(1975, 1976, 1977)
DF<-c(Biomass, Year)

I would like to create (and save) a new raster for each year of my time series through a loop, where all my raster cells originally equal to 1 N[N==1] are replaced by the biomass value found in DF for that specific year.

For example, all the cells originally equaling 1 would be replaced by 0.9 and the raster would be saved as N-1975.

The idea would be to create a loop, but I cannot find anything on looping values of a dataframe into a raster.

I would like to end up with one raster per year "N-1975", "N-1976"... Thank you !


Solution

  • I ended up finding how to solve this issue, so I will post it here in case anybody runs into the same problem :)

    N_loop <- N
    years <- 1975:2020
    
    for(i in seq(length(years))){
      N_loop[N == 1] <- DF$Biomass[i]
      writeRaster(N_loop, paste0("N", years[i], ".asc"), overwrite = TRUE)
    }