David
David

Reputation: 315

How to stop lapply from printing into the console?

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?

Upvotes: 1

Views: 791

Answers (1)

David
David

Reputation: 315

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.

Upvotes: 3

Related Questions