Write CSV with coordinates using R package sf
Asked Answered
A

3

6

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"))
Agretha answered 4/8, 2017 at 20:39 Comment(2)
Can you make your example reproducible? Perhaps run dput(input) and copy paste it here.Cathode
I've added an example.Agretha
A
10

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")
Agretha answered 8/8, 2017 at 12:53 Comment(0)
A
4

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.

Archle answered 17/8, 2017 at 21:44 Comment(1)
Thanks Edzer, agreed that the methods should be consistent but this is also probably an extremely common need. Your code is easier than what I wrote, but still not as easy as something like st_write(input, "output.csv", coords = TRUE) which I thought might exist. The layer_options argument works well for me though!Agretha
E
3

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)

Effeminate answered 7/8, 2017 at 21:39 Comment(2)
Thanks Cole, I appreciate the effort on this but I think your solution is not really easier, it's essentially the same code as the question but repackaged a bit. I was hoping there was something I missing that would be like st_write(input, "output.csv", coords = TRUE).Agretha
Agreed, I wish there was still a "non-hacky" way to append the coordinates. Useful when you are using coordinates as an input to a model.Effeminate

© 2022 - 2024 — McMap. All rights reserved.