Loop through categories in a column and perform interpolation on only those records

1.3k views Asked by At

I have a data frame, with sampling locations. I would like to select data for each unique species, so loop through all the unique species names, and create an interpolated layer for each species. Then name the result by species name. The interpolation part is working fine….I just can’t figure out how to loop through each species name and do the naming….. I've pasted the working code below for selecting one species name and creating an interpolated layer.

                          SP_NAME        sno       swgt    latdd     londd
1              ILLEX ILLECEBROSUS 33.7542857 2.94582857 43.28667 -60.99367
2        CHLOROPHTHALMUS AGASSIZI 13.2971429 0.09205714 43.28667 -60.99367
3              ILLEX ILLECEBROSUS  0.9657143 0.16417143 43.94750 -58.72417
4              ZOARCES AMERICANUS  0.9657143 0.02897143 43.94750 -58.72417
5               AMBLYRAJA RADIATA  2.0457143 1.00240000 43.86483 -59.19717
6 MYOXOCEPHALUS OCTODECEMSPINOSUS  1.0228571 0.10228571 43.86483 -59.19717


setwd("C:/Michelle/Michelle/R/WCTS/Boundaries")
strata <- readOGR(".", "SurveyStrataWGS84")
strata<-spTransform(strata,CRS("+proj=utm +zone=20 ellps=WGS84"))

es_tows1 <- es_tows[which(es_tows$SP_NAME == "HIPPOGLOSSOIDES PLATESSOIDES"),]

ext = extent(strata)
rb <- raster(ext, ncol=554, nrow=279)
stratar <- rasterize(strata, rb)
plot(stratar)
idw.grid<- rasterToPoints(stratar, spatial=TRUE)
gridded(idw.grid) <- TRUE
proj4string(es_tows1) <- CRS("+proj=utm +zone=20 ellps=WGS84")

idw(log(es_tows1$swgt+ 0.00001) ~1 , es_tows1, idw.grid)

pal <- colorRampPalette(rev(brewer.pal(11, "Spectral")))(100)
spplot(idw.out, "var1.pred", col.regions=pal)
1

There are 1 answers

3
Robert Hijmans On BEST ANSWER
library(rgdal)
library(raster)
strata <- readOGR(".", "SurveyStrataWGS84")
strata <- spTransform(strata,CRS("+proj=utm +zone=20 ellps=WGS84"))
ext <- extent(strata)
rb <- raster(ext, ncol=554, nrow=279)
# I think this is all you need to do here 
idw.grid <- as(rb, 'SpatialGrid')

# list of species
species <- unique(es_tows$SP_NAME)

for (sp in species) {
    es_tows1 <- es_tows[es_tows$SP_NAME == sp, ]
    out <- idw(log(es_tows1$swgt+ 0.00001) ~1 , es_tows1, idw.grid)
    # ... save the results ....
    writeRaster(raster(out), filename=sp)
}