in a sf object with ast_point column, how can one create additional numeric columns latand lon?
demo(nc, ask = FALSE, echo = FALSE)
nc <- st_centroid(nc)
nc$lat <- ....
nc$lon <- ....
EDIT: obs: I belive in Postgis it would be something like st_x and st_y
EDIT2: changed data.frame for sf as it seemed to be causing confusion
data.frames can't have an st_point column; otherwise they work as data.frames. This is not an sf related issue; pls read into how R works.
I understand how R works...
Are you referring to the fact that I used the word data.frame instead of sf? Anyway, I edited the original post with sf (edit2).
Flowing sf vignette1 I thought you could use either word interchangeably:
"As attributes are typically stored in data.frame objects (or the very similar tbl_df), we will also store feature geometries in a data.frame column.
sf, the table (data.frame) with feature attributes and feature geometries, which contains"
in any case, how to add numeric coluns lat and lon to a sf object?
Hey @lucasmation, here's a function I wrote a while back that will probably accomplish what you want.
library(sf)
library(dplyr)
geometry_to_lonlat <- function(x) {
if (any(sf::st_geometry_type(x) != "POINT")) {
stop("Selecting non-points isn't implemented.")
}
coord_df <- sf::st_transform(x, sf::st_crs("+proj=longlat +datum=WGS84")) %>%
sf::st_coordinates() %>%
dplyr::as_tibble() %>%
dplyr::select(X, Y) %>%
dplyr::rename(lon = X, lat = Y)
out <- sf::st_set_geometry(x, NULL) %>%
dplyr::bind_cols(coord_df)
return(out)
}
In general, I've found it easier to get answers on stackoverflow than github. There's a whole #sf tag!
@karldw tks. This works!
(for a general function, I don't think the reprojection should be included.
This seems more natural:
x %>% st_transform( sf::st_crs("+proj=longlat +datum=WGS84")) %>% geometry_to_lonlat
)
tks
Sorry for my blunt earlier reply; I clearly misunderstood your question.
@edzer , no worries. I think adding functions st_x and st_y to sf wuold be nice
@lucasmation also take a look at https://github.com/r-spatial/sf/issues/284
> nc = st_centroid(nc)
> st_x = function(x) st_coordinates(x)[,1]
> st_x(nc)[1:3]
1 2 3
-81.49823 -81.12513 -80.68573
IMO, functions that trivial clobber the namespace.
Most helpful comment
IMO, functions that trivial clobber the namespace.