R rgdal::readOGR issue with file path refering to linux home directory

331 views Asked by At

This isn't a huge deal, but does anyone know why:

readOGR('~/documents/zipcodes', 'zipcodes')

Returns: "Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding, use_iconv = use_iconv, : Cannot open file"

When this:

setwd('~/documents/zipcodes')
readOGR('.', 'zipcodes')

Works perfectly?

1

There are 1 answers

0
loki On BEST ANSWER

you can either use tools::file_path_as_absolute() like this:

library(tools)
readOGR(file_path_as_absolute('~/documents/zipcodes'), 'zipcodes')

or

path.expand() as hrbrmstr mentioned in his comment:

readOGR(path.expand('~/documents/zipcodes'), 'zipcodes')

Another, more inconvenient way would be to use base::dirname() in combination with paste0():

readOGR(paste0(dirname('~/documents/zipcodes'), 'zipcodes'), 'zipcodes')