ZRoss
ZRoss

Reputation: 1479

Write CSV with coordinates using R package sf

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

Answers (3)

Edzer Pebesma
Edzer Pebesma

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

ZRoss
ZRoss

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

cole
cole

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

Related Questions