I am trying to open a shapefile (or the directory of the shapefile) in the same directory as my R file. I open it the following way:

x<-c(farm,field,"ec",2017) #farm and field are variables that hold strings
file<-paste(x, collapse="_") #add underscore between each word so it picks up the filename
ec <- readOGR(".", file) #read the file

When I try to run the file with Rscript, I get the following error:

Cannot open data source
Calls: readOGR -> suppressMessages -> withCallingHandlers -> ogrInfo
Execution halted

Even when I use 'read_sf' I still get a "cannot open file" error message and the code stops. How do I fix this?

EDIT: so the path to my shapefile folder(the directory that holds the .shp) "farm_field_ec_2017" is in the directory


my R script is also in this same path. I still cannot figure out my problem.

  • 1
    Have you tried specifying a quoted name, rather than one constructed by code? It helps to check that your shapefile is, in fact, not corrupted, before you assume that there is an issue. It very well could be that the results of your "file" variable are the culprit and not the functions that you are calling. Since we do not know what the "farm" and "field" objects look like there is no way for us to check expected results. Does the result of "file" look something like this: farm_field_ec_2017? Are you in the correct working directory? – Jeffrey Evans Aug 30 '18 at 17:46
  • @Ammar Hoque, what is the path to your shapefile? – Taras Aug 30 '18 at 19:14
  • @Taras I edited my post for more information. Let me know if it helps. – Ammar Hoque Aug 30 '18 at 19:24

Try this snippet of code. It has an error check to see if the specified shapefile actually exists in the working directory. I tried to follow your workflow, with defining variables, but please note that the farm and field variables cannot be more than one value, unless you implement an iterator and index the call to the variables ie., paste(c(farm[i], field[i],"ec", year[i]), collapse="_").


  farm = "farm1"
  field = "field1"
  year = 2017

file <- paste(c(farm, field,"ec", year), collapse="_") 

if( !paste0(file,".shp") %in% list.files() ) {
  cat("Shapefile", file, "does not exist in", getwd(), "\n")
} else {
  ec <- rgdal::readOGR(getwd(), file)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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