How to convert a spatial dataframe back to normal dataframe?
Asked Answered
G

1

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 ?

Glazunov answered 17/2, 2012 at 18:52 Comment(0)
H
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)
Hl answered 17/2, 2012 at 19:6 Comment(5)
Thanks for the answer. Do you know how can I convert xy from SpatialCoordinates to standard values in degrees?Phago
That'll of course depend on the coordinate reference system of the x-y coordinates. In general, though, you can use sp:spTransform(). Here is one example; although it happens to be going in the opposite direction (i.e. transforming away from long-lat), the idea is the same.Bookish
and how can I make it reverse? I tried switching the values in CRS("+proj=longlat +datum=WGS84"), it doesn't work.Phago
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.Bookish
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] (#39500499).Phago

© 2022 - 2024 — McMap. All rights reserved.