I have a shapefile with three columns: gid, which is the ID, rud, the variable I am interested in, and geometry.
I am trying to export that shapefile to csv with the following code:
write.csv(grid, "path\\grid_rud.csv")
where grid is my shapefile. However, the CSV file has not just three columns, it appears very weird (look picture below). I have tried adding col.names or row.names, but the result is the same.
I think it is because of the geometry column. I have tried to remove the column, and after export it:
grid = grid %>% select('gid','rud')
However, the column geometry does not disappear. Any idea how can I export my file to a csv? I am just interested in export columns gid and rud.
To get rid of geometry column you must first reclass your grid
sf object to something else, i.e. to a data.frame. For that there's sf::st_drop_geometry()
, though as.data.frame()
, as_tibble()
and the likes would work too.
Or if you happen to read data from Shapefile but not care about shapes at all, you can import just the attribute table from dbf file.
library(dplyr)
# nc example from sf library
nc <- sf::st_read(system.file("shape/nc.shp", package="sf"))
# select 2 columns from sf object, geometry is still there
nc %>% select(NAME, CNTY_ID) %>% head()
#> Simple feature collection with 6 features and 2 fields
#> Geometry type: MULTIPOLYGON
#> Dimension: XY
#> Bounding box: xmin: -81.74107 ymin: 36.07282 xmax: -75.77316 ymax: 36.58965
#> Geodetic CRS: NAD27
#> NAME CNTY_ID geometry
#> 1 Ashe 1825 MULTIPOLYGON (((-81.47276 3...
#> 2 Alleghany 1827 MULTIPOLYGON (((-81.23989 3...
#> 3 Surry 1828 MULTIPOLYGON (((-80.45634 3...
#> 4 Currituck 1831 MULTIPOLYGON (((-76.00897 3...
#> 5 Northampton 1832 MULTIPOLYGON (((-77.21767 3...
#> 6 Hertford 1833 MULTIPOLYGON (((-76.74506 3...
# drop geometry, select 2 columns from resulting data.frame
nc_df <- sf::st_drop_geometry(nc)
nc_df %>% select(NAME, CNTY_ID) %>% head()
#> NAME CNTY_ID
#> 1 Ashe 1825
#> 2 Alleghany 1827
#> 3 Surry 1828
#> 4 Currituck 1831
#> 5 Northampton 1832
#> 6 Hertford 1833
# if you don't care about geometry, you can read just the dbf of Shapefile
nc_dbf <- foreign::read.dbf(system.file("shape/nc.dbf", package="sf"))
nc_dbf %>% select(NAME, CNTY_ID) %>% head()
#> NAME CNTY_ID
#> 1 Ashe 1825
#> 2 Alleghany 1827
#> 3 Surry 1828
#> 4 Currituck 1831
#> 5 Northampton 1832
#> 6 Hertford 1833
Created on 2023-02-26 with reprex v2.0.2