Reputation: 1479
I'm wondering if there is an easy way to write a CSV of a point sf
object (sf
R package) that includes the coordinates.
You can use st_write(input, "output.csv")
and it will write a CSV without coordinates. My hack for writing a file with coordinates is:
coords <- st_coordinates(input)
input_dat <- input %>% st_set_geometry(., NULL)
input_dat <- cbind(input_dat, coords)
But it seems there must be a simpler way.
As requested, here is the setup for the code above:
input <- data.frame(ID = 1:10, longitude = rnorm(10), latitude = rnorm(10))
input <- st_as_sf(input, coords = c("longitude", "latitude"))
Upvotes: 7
Views: 5355
Reputation: 4121
You want a different treatment for POINT simple feature geometries from all other geometry types for something as basic as as.data.frame
; I consider that feature creep. I think
cbind(as.data.frame(input), st_coordinates(input))
is easy enough, for this particular case.
st_write
is meant to be your portal to all GDAL drivers and nothing more, it will do nothing with the data first, or manipulate GDAL settings by itself.
Upvotes: 5
Reputation: 1479
I was sent to the solution by Jakub Nowosad. He pointed me to this github issue which was solved by Etienne B. Racine.
Apparently GDAL has a flag that allows you to include the coordinates. So:
st_write(input, "output.csv", layer_options = "GEOMETRY=AS_XY")
Upvotes: 11
Reputation: 586
There should be an easier way, I agree. The as.data.frame()
method for sp
objects appends the coordinates and I feel like there should be one for sf
objects too. But for now, how about:
input %>%
cbind(., st_coordinates(.)) %>%
st_set_geometry(NULL)
Upvotes: 3