Flyto
Flyto

Reputation: 686

R : How to write an XYZ file from a SpatialPointsDataFrame?

I have a SpatialPointsDataFrame which has one attribute (let's call it z for convenience) as well as lat/long coordinates.

I want to write this out to an XYZ file (i.e. an ASCII file with three columns).

Initially I tried

write.table(spdf, filename, row.names=FALSE)

but this wrote the z value first, followed by the coordinates, on each row. So it was ZXY format rather than XYZ. Not a big deal, perhaps, but annoying for other people who have to use the file.

At present I am using what feels like a really horrible bodge to do this (given below), but my question is: is there a good and straightforward way to write a SPDF out as XYZ, with the columns in the right order? It seems as though it ought to be easy!

Thanks for any advice.

Bodge:

dfOutput <- data.frame(x = coordinates(spdf)[,1], y = coordinates(spdf)[,2])
dfOutput$z <- data.frame(spdf)[,1]
write.table(dfOutput, filename, row.names=FALSE)

Upvotes: 5

Views: 3157

Answers (3)

a different ben
a different ben

Reputation: 4008

Following up on Noah's comment about a method like coordinates but for data values: The raster package has the getValues() method for returning the values of a SpatialPointsDataFrame.

library(raster)

spdf <- raster('raster.sdat')
write.table(
    cbind(coordinates(spdf), getValues(spdf)), 
    file = output_file, 
    col.names = c("X", "Y", "ZVALUE"),
    row.names = FALSE,
    quote = FALSE
    )

Upvotes: 1

Noah
Noah

Reputation: 1404

Why not just

library(sp)
spdf <- SpatialPointsDataFrame(coords=matrix(rnorm(30), ncol = 2), 
                               data=data.frame(z = rnorm(15)))


write.csv(cbind(coordinates(spdf), spdf@data), file = "example.csv", 
          row.names = FALSE)

Upvotes: 4

Roman Luštrik
Roman Luštrik

Reputation: 70653

You can write to a .shp file using writeOGR from rgdal package. Alternatively, you could fortify (from ggplot2) your data and write that as a csv file.

Upvotes: 2

Related Questions