0

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.

1
  • what do you mean by ascii here? ASCII? Not sure if the tag you applied is relevant...
    – Vasily A
    Oct 26, 2020 at 1:20

1 Answer 1

2

rasterize() function has field argument, so you can call it like this:

result[[i]] <- rasterize(spi, tempraster, 
                         field=selection[selection$scientific_name == spp[i], "total"], 
                         fun=sum,
                         filename=fname, background = 0, 
                         overwrite = TRUE)
3
  • That is exactly it, I knew I could use a different function, e.g. rasterize, but didn't know how to edit it into the existing code - thank you!
    – TJeff
    Oct 26, 2020 at 4:33
  • glad if it helped. If your question is solved, feel free to mark it as such. Also, maybe consider changing the title of your question - I think it is not really about for loop, rather about use of rasterize().
    – Vasily A
    Oct 26, 2020 at 4:40
  • Also, note that I removed the fun=count part from your code. With it, rasterize would be placing number of occurrences in the cell. When fun is not defined, rasterize() uses the last() function - which I think is also not correct in your usecase, you should rather use fun=sum. I have now added it to my answer.
    – Vasily A
    Oct 26, 2020 at 4:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.