24

This is a basic question but unfortunately I could not find the relevant command elsewhere.

Is there a way i can convert a Spatial Points Dataframe to an ordinary dataframe in R.

e.g. if the ordinary dataframe is df with Lat, Lon as location coordinates I can obtain a spatial df as:

coordinates (df)= ~Lat + Lon

How is the reverse possible or is it even possible ?

joran
  • 169,992
  • 32
  • 429
  • 468
user2760
  • 2,273
  • 7
  • 25
  • 34

1 Answers1

37

as.data.frame() does just what you are looking for:

library(sp)
# Construct a SpatialPointsDataFrame
data(meuse)
xy <- meuse[1:2]
df <- meuse[-1:-2]
SPDF <- SpatialPointsDataFrame(coords=xy, data=df)

# And then convert it (back) to a data.frame
DF <- as.data.frame(SPDF)
Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
  • Thanks for the answer. Do you know how can I convert xy from SpatialCoordinates to standard values in degrees? – Rotail Sep 14 '16 at 20:39
  • That'll of course depend on the [coordinate reference system](https://en.wikipedia.org/wiki/Spatial_reference_system) of the x-y coordinates. In general, though, you can use `sp:spTransform()`. Here is [one example](http://stackoverflow.com/a/18641016/980833); although it happens to be going in the opposite direction (i.e. transforming away from long-lat), the idea is the same. – Josh O'Brien Sep 14 '16 at 21:24
  • and how can I make it reverse? I tried switching the values in CRS("+proj=longlat +datum=WGS84"), it doesn't work. – Rotail Sep 14 '16 at 22:00
  • That should work if you've got a `SpatialPoints` object (for instance) with a proper CRS. (You can see that it does work by running the example given in the answer I linked just above and then doing `spTransform(res, CRS("+proj=longlat +datum=WGS84"))` to successfully reverse the transformation. Since this isn't working on your data, it must be a problem with your `Spatial*` object rather than with the `spTransform()` command. Cheers. – Josh O'Brien Sep 15 '16 at 01:24
  • I could start from the example and converting back and forth. The problem is that when I want to start from NAD83 State Plane Coordinates, it doesn't work. I tried this: xy <- data.frame(ID = 1, X = c(577430), Y = c(2323270)) coordinates(xy) <- c("X", "Y") proj4string(xy) <- CRS("+proj=longlat +datum=WGS84") ## res <- spTransform(xy, CRS("+proj=utm +zone=51 ellps=WGS84")). Please see more details on what I stuck in [here] (http://stackoverflow.com/questions/39499999/converting-nad83-state-plane-coordinates-to-ws84-standard-lon-lat-in-degrees/39500834#39500834). – Rotail Sep 15 '16 at 01:53