I have a KML file which was created using Google's My Maps.
The original file can be downloaded here:
Google My Maps
Using R, I can import this using the "readOGR" function of the rgdal library
This brings the KML file in as a SpatialPointsDataFrame (SPDF) – which i am calling asf52
In this SPDF, the spatial data is contained under @coords and is readily extracted into a dataframe using code like
df <- data.frame(asf52@coords[,1:2])
However, I am struggling to come up with a way to neatly extract the the non-spatial data – contained under @data$Description – and turn it into a dataframe with a column for each variable.
Best Answer
You don't need to call
data.frame()
around the extract - the@data
slot already is a data.frame. Just doto pull out a copy. That said, you may be better served by using the newer
sf
library for this task:There is more than one layer in your KML - list them with e.g.
Use
read_sf()
with thelayers
argument to choose your point data specifically and read it in.read_sf()
defaults to stringsAsFactors = FALSE which may be preferable.To get a plain dataframe, just drop the geometry as follows:
EDIT: I see your secondary issue now; it looks like neither
sf
norsp
look at the<ExtendedData>
tags that hold the attribute data you want (open the KML in Notepad++ if you want to see what I mean). QGIS does detect and import them as separate attribute columns, so @Jella's advice is sound. I'm not sure if the issue here lies withsf
/sp
or GDAL, but it may be worth raising an issue of thesf
github page.In the meantime, your instinct to go with
tidyr
functions is sound, its just a little tricky to get a clean separation. The following looks pretty good: