1

I'm trying to fill in counties of states with data to help with a project I'm working on. I found a wonderful answer here on how to add county names to the county map of New York. I was able to use it to help on a few states, but am striking out when I attempt to use the maps of Texas and Louisiana. For reference, this is what I'm typing:

library(ggplot2)
library(sp)
library(maps)
getLabelPoint <- function(county) {Polygon(county[c('long', 'lat')])@labpt}
df <- map_data('county', 'louisiana')
centroids <- by(df, df$subregion, getLabelPoint)

It's at that point R spits out "Error in Polygon(county[c("long", "lat")]) : ring not closed"

I honestly don't even know where to start to fix this, so any help or even an alternative method would be awesome.

Community
  • 1
  • 1
joblaska
  • 35
  • 1
  • 3

1 Answers1

1

The problem stems from splitting the dataframe on the wrong variable. You should use group, not subregion (see end of post), however, rather than by how about trying sapply instead? I think it gives nicer formatted and more easily useable output:

 t( sapply( unique(df$group) , function(x) Polygon(df[df$group==x,c("long","lat")])@labpt ) )
#          [,1]     [,2]
# [1,] -92.40716 30.29909
# [2,] -92.82364 30.65532
# [3,] -90.91371 30.20234
# [4,] -91.06610 29.90319
# [5,] -92.00565 31.08009
# [6,] -93.34896 30.65511
# ..........

edit

the problem was more simple than I imagined! You were splitting on the wrong group variable, should be group NOT subregion. However, my solution gives nicer more useable output for placing labels than the funny formatting of by (IMHumbleO)

centroids <- by(df, df$group, getLabelPoint)
Simon O'Hanlon
  • 58,647
  • 14
  • 142
  • 184
  • AWESOME, thanks. Splitting by subregion causing the issue makes sense. After I dug through, each of these states has a county (or parish, whatever Louisiana) with two polygons associated. I do like sapply more too, so I'm definitely going to use that. – joblaska Jun 21 '13 at 14:23
  • @midwestoast happy to help, glad you found it useful! :-) – Simon O'Hanlon Jun 21 '13 at 14:58