Reputation: 111
I have a set of UTM metric points that I would like to convert to latitude and longitude decimal points using the sf environment.
The dataset I have looks like this:
df <- data.frame(longitude=c(4585434,4588904,4586694),
latitude=c(430060.8,430960.8,432427.2),
street=c("74 JOSEP SERRANO", "30 LLOBERA","4 SANT ILDEFONS"),
number=c(45,68,34))
I have only been able to do it under the sp framework.
dfevpo <- SpatialPoints(df[, c("longitude","latitude")], proj4string=CRS("+proj=utm +zone=10"))
longlats <- spTransform(dfevpo, CRS("+proj=longlat")) #transform
longlats.df <- as.data.frame(longlats)
longlats.df$.id <- as.numeric(rownames(longlats.df))
However, the resulting longlats.df
dataset does not include all variables from the original dataset. I guess the order is the same and I could merge it with the original one. However, is there a more intuitive way of doing this? Ideally, I would like to use sf.
Upvotes: 3
Views: 3686
Reputation: 8176
You can use the following code
library(sp)
df <- data.frame(longitude=c(4585434,4588904,4586694),
latitude=c(430060.8,430960.8,432427.2),
street=c("74 JOSEP SERRANO", "30 LLOBERA","4 SANT ILDEFONS"),
number=c(45,68,34))
#Convert the data frame to SpatialPointsDataFrame
coordinates (df)= ~longitude + latitude
#Assign a projection to it
proj4string(df) <- CRS("+proj=utm +zone=10")
#Projection transformation
longlats <- spTransform(df, CRS("+proj=longlat"))
#Convert it to data frame
longlats.df <- as.data.frame(longlats)
If you want to implement the whole thing using sf
package, you can use the following code
df <- data.frame(longitude=c(4585434,4588904,4586694),
latitude=c(430060.8,430960.8,432427.2),
street=c("74 JOSEP SERRANO", "30 LLOBERA","4 SANT ILDEFONS"),
number=c(45,68,34))
#Conversion of data frame to sf object
df_sf <- st_as_sf(x = df,
coords = c("longitude", "latitude"),
crs = "+proj=utm +zone=10")
#Projection transformation
sfc = st_transform(df_sf, crs = "+proj=longlat +datum=WGS84")
#Convert it to data frame
sfc_df <- as.data.frame(sfc)
Upvotes: 7