As of May 31, 2023, we have updated our Code of Conduct.
3 of 3
Rollback to Revision 1 - Edit approval overridden by post owner or moderator
TJeff
  • 29
  • 8

Creating for loop, df to ascii with x y z

I have a dataframe:

enter image description here

In total more than 3 million rows and 1800 species (scientific name)

The code below creates an empty raster at 0.5 degree scale..

library(raster)
ext <- extent(-180.0, 180, -90.0, 90.0)
gridsize <- 0.5
tempraster<- raster(ext, res=gridsize)
crs(tempraster) <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"`

#and then the code below fills that raster with x y data one species at a time, creating an ascii as per the scientific name, with a 1 where the species is and a 0 where it is not.

selection<-animals
spp <- unique(animals$scientific_name)
result <- list()
for (i in 1:length(spp)) {
  spi <- selection[selection$scientific_name == spp[i], c("lon", "lat")]      
  fname <- paste0(spp[i], ".asc")
  result[[i]] <- rasterize(spi, tempraster, fun="count", filename=fname, background = 0, overwrite = TRUE)}

I would like to adjust this code so that instead of the resulting ascii having a 1 where the species is, it uses the value from the total column. Unfortunately I am a beginner at for loops and other functions so am asking for any help.

TJeff
  • 29
  • 8