R Package for CShapes Examples
This is a collection of R code examples using the cshapes package, taken from requests I received from cshapes users. I will keep posting new examples here -- suggestions and contributions welcome!
- Extracting distances for one country only (e.g. Canada, COW code 20):
m <- distmatrix(as.Date("2000-1-1"), type="capdist", useGW=F)
m["20",]
Explanation: we compute the distance matrix for the desired date, and then extract the row (or column) corresponding to the country. Rows and columns in the distance matrix m are labeled by country codes, which R treats as strings. Thus, we need to put the country code in quotes, otherwise R would return the 20th row. - Computing distances of capital cities to the equator:
cshp.2000 <- cshp(as.Date("2000-1-1"))
ce.dist <- abs(cshp.2000$CAPLAT)*pi*6378.1/180
res <- cbind(cshp.2000$COWCODE, ce.dist)
Explanation: we obtain the cshapes GIS dataset using the cshp() function for the desired date. Using the latitude coordinates of the capital (field CAPLAT), we compute the arc length of the capital to the equator, assuming the earth is a perfect sphere with radius 6378.1 km. The last line simply joins the COW codes and the corresponding distances. - Computing dyadic distances for all years in the post-WWII period:
GW <- TRUE # wether to use the Gleditsch & Ward country codes
disttype <- "capdist" # what type of distance we want to compute
result <- distlist(as.Date("1946-6-30"), type=disttype, useGW=GW)
result <- result[result$ccode1 < result$ccode2,] # we drop duplicate dyads
result$year <- 1946for (year in 1947:2008) {
date.current <- paste(year, "6", "30", sep="-")
result.current <- distlist(as.Date(date.current), type=disttype, useGW=GW)
result.current <- result.current[result.current$ccode1 < result.current$ccode2,]
result.current$year <- year
result <- rbind(result, result.current)
}
write.table(result, filename, row.names=F) # save complete table to file