Unable to open gpkg files

geopackagersf

I am trying to load several gpkg files into R but got some problems.
Initially this code works:

library("dplyr")
library("rgdal")
library("sp")
library("st")
library("sf")

setwd("C:\Users\filename.gpkg")
temp = list.files(pattern=".gpkg")
myfiles = lapply(temp, st_read)

Also, this works for each file (but I have more than 15 files):

st_read("filename.gpkg", layer= 'layerx')

But I need to specify the layer, so I code this way:

temp = list.files(pattern=".gpkg", full.names= TRUE)
tem2 = lapply(temp, st_read(dsn= '.',layer= 'layerx'))

But does not work, produce this error:

Error: Cannot open "C:\Users\"; The source could be corrupt or not supported. See `st_drivers()` for a list of supported formats.

Any ideas on how to solve this?
BR

Best Answer

In lapply, the second argument needs to be a function definition (not a function call).

Please try replacing the last expression with:

tem2 = lapply(temp, function(x) st_read(x, layer= 'layerx'))