首页 > 解决方案 > 如何阻止 lapply 打印到控制台?

问题描述

我正在将一堆 shapefile 读入 R 并lapply用于在一堆文件中运行它。现在,代码工作正常,但它会在控制台中打印很多信息。我试图摆脱它,以便控制台更清洁。

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))

代码运行得非常快,但是对于每个文件都会打印出如下信息:

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

注意:我用“xxxx”代替了实际值。

我想阻止它将此信息打印到控制台中。我已经尝试过这里推荐lapply的包装和函数。两种方法都不起作用。有任何想法吗?lapplyinvisible()

标签: rconsoleapply

解决方案


使用capture.output(load_shapefiles(x))invisible(load_shapefiles(x))没有工作的地方工作。

感谢 Rui Barradas 的回答

编辑:st_read有一个调用的参数quiet,它确定它是否会打印有关它正在读取的文件的信息。设置quiet为 TRUE 消除了将函数包装在capture.outputor中的需要invisible


推荐阅读