1

I'm reading a bunch of shapefiles into R and using lapply to run it across a bunch of files. Right now, the code works fine, but it prints a lot of info into the console. I'm trying to get rid of that so that the console is cleaner.

load_shapefiles <- function(file_name){
#grabs the last two digits of the year for the current file
partial_year <- str_sub(file_name, start = 9, end = 10)
#read in files
st_read(dsn = sprintf("data/%s", file_name), layer = sprintf("Census_sum_%s", partial_year))
}

#apply the loading function across a list of file names
list_data <- lapply(list_filenames, function(x) load_shapefiles(x))

The code runs really quickly, but for every file prints out some information like this:

Reading layer 'Census_sum_17' from data source xxxx using driver ESRI Shapefile Simple feature collection with xxxxx features and xxxxxx fields geometry type: POLYGON dimension: XY bbox: xmin: xxxx ymin: xxxxxx xmax: xxxxxx ymax: xxxxxxx epsg (SRID): NA proj4string: xxxxx

Note: I substituted 'xxxx' for actual values.

I'd like to keep it from printing this info into the console. I've tried wrapping lapply and the function within lapply in invisible() as recommended here. Neither approach worked. Any ideas?

David
  • 195
  • 1
  • 1
  • 10
  • 3
    Maybe `invisible(load_shapefiles(x))`, since it's this function that is printing those messages. Or `capture.output` instead of `invisible`. – Rui Barradas Mar 06 '19 at 19:19
  • `capture.output` worked. For some reason, `invisible` didn't do it. Thanks for the help! – David Mar 06 '19 at 20:09

1 Answers1

2

Using capture.output(load_shapefiles(x)) worked where invisible(load_shapefiles(x)) did not.

Thanks to Rui Barradas for the answer

EDIT: st_read has a parameter called quiet which determines whether or not it will print info about the file that it is reading. Setting quiet to TRUE eliminates the need to wrap the function in capture.output or invisible.

David
  • 195
  • 1
  • 1
  • 10