I have a shapefile "grid" that is basically a grid map of US and Canada. Each grid has its own specific ID (grid_code). I also have a csv file that has the relative abundance values of bird species that correlate to respective grids. Because each species has their unique distribution, the species table only includes a subset of all the available grid codes.
I am trying to create a thematic map showing the relative abundance of each species. For this, I am first joining the csv file to the attribute table of the grid shapefile using leftjoin function, where grid_code is the common column. After specifying the color palette for the tmap, I am creating a png file for each species' relative abundance.
The following code works fine when I manually put in a value for i; however, when I run the entire code, it stops after the leftjoin function, and creates a blank png file for each species. I have tried several things but am having no luck fixing this. Is it just a matter of placement of codes or is there something majorly wrong with my for-loop?
Thanks.
# reading in csv file with relative abundance info
rel_ab <- read.csv("ra_test.csv", h=T, stringsAsFactors = F)
# specifying color palette for tmap
colfunc <- colorRampPalette(c("lightpink", "red"))
# running for loop code where I'm reading and reprojecting the grid
# shapefile each time, then joining it to the species table, and finally
# plotting the tmap
# only want to work with one species at a time, so first:
ra <- unique(rel_ab$species)
for (i in ra){
species <- rel_ab[which(rel_ab$species == i),]
grid <- readOGR(dsn = "grid_clip", "grid") # reading grid shapefile
grid83<- spTransform(grid, CRS("+init=epsg:5070")) # transorming shapefile
grid83@data <- left_join(grid83@data, species)
# grid83 now contains a column that includes all the grid codes PLUS a
# column for relative abundance values (V2) for species i. Again, because a
# species is not found in every part of US/CANADA, there are a lot of V2
# rows that are NA.
# Here is what grid83@data looks like:
head(grid83@data)
AREA PERIMETER TEMP_ TEMP_ID GRID_CODE BCR STATE STATE_CODE STRATA_ KMSQ X V2 V3 species
1 463738112 87471.12 6548 92624 6981 5 ALK 3 S94 461 NA NA NA <NA>
2 463749632 87485.10 6551 92625 6982 5 ALK 3 S94 461 NA NA NA <NA>
3 463766720 87499.32 6554 92626 6983 4 YT 93 S68 461 NA NA NA <NA>
png(width = 1000, height = 1000, filename = paste("RA_maps/",i,".png", sep=""))
tm_shape(grid83)+
tm_fill("V2", title = "BBS Summer Distribution", textNA = "None counted",
style = "fixed", breaks = c(Inf, 100, 30, 10, 3, 1, 0.05), colorNA = "white", palette = colfunc(6))+
tm_shape(uscan83)+
tm_borders(lwd = 1.5)+
tm_shape(gray83)+
tm_fill(col="grey85")+
tm_borders()+
tm_layout(
inner.margins = c(.02, .02, .02, .02),
legend.title.size = 1.8,
legend.text.size = 1,
legend.bg.color = "white",
legend.bg.alpha = 0,
legend.width = 0.22)
dev.off()}