'Read only the first line of a shapefile using SF in r

I am building a function to generate metadata for shapefiles in R.

One of my ideas was to get the name and class of each column in an SF (in case there is a massive SF and you don't have to wait to read all the data to get the names of them), for that I was looking into the read_sf function, specifically to at the query argument.

Following the example from this link, I saw that you can filter by the values of a column to get a smaller dataset for example:

library(sf)

nc = st_read(system.file("shape/nc.shp", package="sf"))

If I know the name of the columns beforehand I could filter with something like this:

nc_sql = st_read(system.file("shape/nc.shp", package="sf"),
                 query = "SELECT NAME, SID74, FIPS FROM \"nc\" WHERE BIR74 > 20000")

But of course the goal is to get the column names, so I would like to use something similar to what I see in this answer.

I have tried this code among other unsuccessful tries:

nc_sql = st_read(system.file("shape/nc.shp", package="sf"),
                 query = "SELECT TOP 1 * FROM \"nc\"")

Any help would be greatly apprecieated



Solution 1:[1]

You can pass a SQL query with read_sf. It should look like this

library(sf)    

data = read_sf('file.gpkg', query = 'SELECT * from layername LIMIT 1')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Calleros