Home > Enterprise >  Looping dataframe values into a raster through time
Looping dataframe values into a raster through time

Time:03-04

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 !

CodePudding user response:

What spatial information are you working with? If you have a simple xy coordinate system you can use rasterfromXYZ(df) to give you a raster layer for each column of your data frame, as long as your first two columns are x and y coordinates respectively. If you're using some other projection then you can specify it in the function: (https://rdrr.io/cran/raster/man/rasterFromXYZ.html)

#make som random data
x<-c(1,4,3,2,4)
y<-c(4,3,1,1,4)

#best to avoid only numbers as col names
X1975<- rnorm(5, 4,1)
X1976<- rnorm(5,5,1)

#make df
df<- cbind(x,y,X1975,X1976)

#make raster
biomass_raster <- rasterFromXYZ(df)


biomass_raster

#returns
class      : RasterBrick 
dimensions : 4, 4, 16, 2  (nrow, ncol, ncell, nlayers)
resolution : 1, 1  (x, y)
extent     : 0.5, 4.5, 0.5, 4.5  (xmin, xmax, ymin, ymax)
crs        : NA 
source     : memory
names      :    X1975,    X1976 
min values : 1.290337, 4.523350 
max values : 4.413451, 6.512719 



#plot all layers: plot(biomass_raster)
#access specific layer by calling biomass_raster$X1975 

CodePudding user response:

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)
}
  • Related