0
votes

So I've got a reflectance dataframe with the first two columns being lon and lat and each column afterwards being a wavelength (where z is the reflectance value):

(but i changed the name of each column after lon and lat to "refl")

#lon, lat, band1, band2, band3, band4, etc.
#x,y,z,z,z,z...
#x,y,z,z,z,z...

I am trying to create a multi-layer raster and can do so with one layer (xyz) through this code:

data<-read.csv("data.csv)
layer1<-data[,c(1:3)] # to select the first two lon and lat column and the band1 column
x <- raster(xmn=151.9124, xmx=151.9146, ymn=-23.4473, ymx=-23.44518, res=0.00001, crs="+proj=longlat +datum=WGS84")
specras <- rasterize(layer1[, c('lon', 'lat')], x, layer1[, 'refl'], fun=mean)

this is how one raster layer looks like plotted

Once I have one raster layer, how to I create a loop to make all the subsequent columns in data into raster layers and then bind them all to make a RasterStack? I have about 1000 band values/columns.

Looking to write something in the form of this but can't seem to get it to work:

for (i in (3:ncol(data))){
  layer<-data[,c(1:2,i)]
  specrast<-rasterize(layer[, c('lon', 'lat')], x, layer[, 'refl'], fun=mean)
  specbrick<-addLayer(specrast)
}
1

1 Answers

0
votes

You should need a loop and be able to use

library(raster)
x <- raster(xmn=151.9124, xmx=151.9146, ymn=-23.4473, ymx=-23.44518, res=0.00001, crs="+proj=longlat +datum=WGS84")
sr <- rasterize(data[, c('lon', 'lat')], x, data[, -c(1:2)], fun=mean)

Your loop could work like this

s <- list()
for (i in (3:ncol(data))){
  s[[i-2]] <- rasterize(data[, c('lon', 'lat')], x, data[, i], fun=mean)
}
sr <- stack(s)