2

I'm not sure if I've used the correct terminology in my title, so please forgive me if that doesn't entirely make sense.

For the sake of reproducing my example, I've created a dummy example. As usual, I pulled the ESRI shapefile from GADM and am using Ethiopia (admin level 1) as an example. I'll describe my problem in terms of this Ethiopia example.

I have a shapefile of the regions of Ethiopia that has been fortified into a data frame. Each region corresponds to a number in the attribute ID_1. I have created a vector, x, of a string of numbers that I need to pull from the Ethiopia shapefile while maintaining all of the rest of the data. Here's my code:

setwd("D:/Mapping-R/Ethiopia")

library(rgdal)
library(ggplot2)
library(rgeos)
library(maptools)
library(plyr)

#read in shapefile 
eth <- readOGR(dsn = "D:/Mapping-R/Ethiopia", layer = "ETH_adm1")

#fortify
eth@data$id <- rownames(eth@data)
eth.f <- fortify(eth, region = "id")
eth.df <- join(eth.f, eth@data, by = "id")

#create dummy vector
x <- 6:9

#try to subset data
test <- eth.df[eth.df$ID_1 == x,]

This final line of code gives me the error

Warning message: In eth.df$ID_1 == x : longer object length is not a multiple of shorter object length

How do I go about performing this subset without an error? I'm still fairly new to R and subsetting, so I feel like there's probably a pretty easy solution, but I can't seem to nail the proper search terms to find an answer. In my real code, it's necessary that the numbers I need to pull (in the example, 6:9) are a named vector, so I'm not sure how to fix the problem.

4

Try

library(rgdal)
library(ggplot2)
library(rgeos)
library(maptools)
library(plyr)
library(raster)

#read in shapefile 
eth <- getData("GADM", country = "Ethiopia", level = 1)

#fortify
eth@data$id <- rownames(eth@data)
eth.f <- fortify(eth, region = "id")
eth.df <- join(eth.f, eth@data, by = "id")

#create dummy vector
x <- 6:9

#try to subset data
test <- eth.df[eth.df$ID_1 %in% x,]

ggplot(eth.df, aes(long, lat, group=group)) + geom_polygon(colour="white")
ggplot(test, aes(long, lat, group=group)) + geom_polygon(colour="white")

The warning tells you that the length of the vector eth.df$ID_1 is not a multiple of the length of the vector x, which is of length 4. By using == you compare eth.df$ID_1[1] to 6, eth.df$ID_1[2] to 7, ... eth.df$ID_1[4] to 9, and eth.df$ID_1[5] again to 6 and so on.

However, you probably want to get all ÌD_1s which are 6 or 7 or 8 or 9. In order to do this, you can use %in%. Check ?`%in%` for help.

  • That's a bingo! I'm surprised that I've never even come across %in% throughout my R mapping. Thanks for the explanation for what the error meant as well! – Lauren Jan 8 '16 at 16:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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