Convert shapefile with lists to data frame in R

To read your shapefile, i recommend you to use rgdal package and its readOGR function, or eventually use readShapeLines from maptools package. These packages rely on the sp package as concerning how the geospatial data is structured in R.

You can do easily this to convert your shapefile into data.frame (ie extract the attributes of the shapefile)

require(rgdal)
foo <- readOGR(dsn=".",layer="ne_10m_roads_north_america")
foo.df <- as(foo, "data.frame")

And that's it!

Note: If we compare readOGR and readShapeLines in term of performance, readShapeLines seems to give better results:

-with readOGR

user  system elapsed
114.48    7.34  123.83

-with readShapeLines

user  system elapsed 
76.28    0.43   78.05

Please read the sp vignette on spatial classes and methods.

vignette(package="sp")[4]
  vignette("intro_sp")

Since there is a slot (@data) that holds a data.frame related to the sp object, no coercion is required.

class(foo@data)
str(foo@data)
( df <- foo@data )

However, it is good practice to operate directly on the @data slot rather than pulling it to a new object. Not only is it more efficient it also avoids breaking the relationship between the row order and the slots in the sp object it relates to.


You can use the Broom package.

Simply run:

my_df <- tidy(foo)