11

Is there a direct way to load a CSV as an sf? I've looked through the sf documentation and nothing jumps out at me, currently using:

my_csv <- read.csv('my_data.csv', header = TRUE)

my_sp <- sp::SpatialPointsDataFrame(coords = data.frame(my_csv$y, 
my_csv$x), data = data.frame(my_csv$data), proj4string = CRS(BNG))

my_sf <- sf::st_as_sf(my_sp)
3

3 Answers 3

16

When you read a CSV with no options the driver doesn't know where the coordinate columns are so returns a data frame:

library(sf)
> st_read("./pts.csv")
Reading layer `pts' from data source `/home/rowlings/Downloads/SO/csv/pts.csv' using driver `CSV'
  id     x     y
1  1  10.1   2.1
2  2   2.4  12.1
3  3   3.2   4.5
Warning message:
no simple feature geometries present: returning a data.frame or tbl_df 

So you need to pass a couple of options that end up telling the OGR driver where the coordinates are:

library(sf)
> st_read("./pts.csv", options=c("X_POSSIBLE_NAMES=x","Y_POSSIBLE_NAMES=y"))
options:        X_POSSIBLE_NAMES=x Y_POSSIBLE_NAMES=y 
Reading layer `pts' from data source `/home/rowlings/Downloads/SO/csv/pts.csv' using driver `CSV'
Simple feature collection with 3 features and 3 fields
geometry type:  POINT
dimension:      XY
bbox:           xmin: 2.4 ymin: 2.1 xmax: 10.1 ymax: 12.1
epsg (SRID):    NA
proj4string:    NA

and there's your sf spatial object.

OGR CSV driver documentation is here: https://gdal.org/drv_csv.html

2
  • 2
    Who downvoted and why? This is still a perfectly correct and, I think, optimal solution to the problem. I don't mind downvotes with constructive comments.
    – Spacedman
    Mar 11, 2020 at 9:05
  • Great answer. I had no idea you could read in a CSV using st_read and convert it to sf in one go.
    – Earlien
    Jun 7, 2021 at 5:16
5

If the column names aren't x and y you can first load csv then convert using st_as_sf.

df = read.csv('file.csv') %>% 
st_as_sf(coords=c("x_col_name","y_col_name"), crs=4326) # remember x=lon and y=lat

If your .csv doesn't have the coordinate columns as numeric data types, you'll have to convert prior to st_as_sf, or use readr::read_csv() to load in the file which will auto detect data types.

You can load in coordinates of any projection just remember to change the crs.

0

I don't have the reputation to respond to the chosen answer, but it didn't work for me because it didn't recognize it as a simple feature even with the option chosen. I found the answer at this post where you use st_as_sf

t=read.csv('tab.csv')
t=st_as_sf(t, coords=c(x,y), crs=4326)
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.