hk47 hk47 - 1 year ago 106
R Question

Choropleth world map

I have read so many threads and articles and I keep getting errors. I am trying to make a choropleth? map of the world using data I have from the global terrorism database. I want to color countries on a factor of nkills or just the number of attacks in that country.. I don't care at this point. Because there are so many countries with data, it is unreasonable to make any plots to show this data.

Help is strongly appreciated and if I did not ask this correctly I sincerely apologize, I am learning the rules of this website as I go.

my code (so far..)

world<- map_data("world")
gtd<- data.frame(gtd)
names(gtd)<- tolower(names(gtd))
gtd$country_txt<- tolower(rownames(gtd))
demo<- merge(world, gts, sort=FALSE, by="country_txt")

In the gtd data frame, the name for the countries column is "country_txt" so I thought I would use that but I get error in, x) : 'by' must specify a uniquely valid column

If that were to work, I would plot as I have seen on a few websites..
I have honestly been working on this for so long and I have read so many codes/other similar questions/websites/r handbooks etc.. I will accept that I am incompetent when it comes to R gladly for some help.

Answer Source

Building on the nice work by @jlhoward. You could instead use rworldmap that already has a world map in R and has functions to aid joining data to the map. The default map is deliberately low resolution to create a 'cleaner' look. The map can be customised (see rworldmap documentation) but here is a start :


#3 lines from @jlhoward 
gtd        <- read.csv("globalterrorismdb_1213dist.csv")
gtd.recent <- gtd[gtd$iyear>2009,]
gtd.recent <- aggregate(nkill~country_txt,gtd.recent,sum)

#join data to a map
gtdMap <- joinCountryData2Map( gtd.recent, 
                               joinCode="NAME" )

mapDevice('x11') #create a world shaped window

#plot the map
mapCountryData( gtdMap, 
                numCats=100 )

Following a comment from @hk47, you can also add the points to the map sized by the number of casualties.

deaths <- subset(x=gtd, nkill >0)