首页 > 解决方案 > 如何在 R 中获取多个文件而不返回值 ($value) 和可见 ($visible) 跟踪

问题描述

假设我有以下.R文件:

R/01_script.R

cat("You are now in 01_script.R")

R/01_script.R

cat("You are now in 01_script.R")

我会将它们放入一个单独的调用/文件WORKFLOW.R中,该文件来自这两个文件:

工作流

source(here::here("R/01_script.R"))
source(here::here("R/02_script.R"))

运行这个,我得到以下打印到控制台:

You are now in 01_script.R
You are now in 02_script.R

如果我尝试将其抽象为一个列表,然后运行sapply​​、lapplypurrr::map,我会收到更详细的输出:

list_of_scripts <- list(
  here::here("R/01_script.R"),
  here::here("R/02_script.R")
)

lapply(list_of_scripts, source)
# You are now in 01_script.RYou are now in 02_script.R[[1]]
# [[1]]$value
# NULL
# 
# [[1]]$visible
# [1] FALSE
# 
# 
# [[2]]
# [[2]]$value
# NULL
# 
# [[2]]$visible
# [1] FALSE

# ...and similar results with either...
sapply(list_of_scripts, source)

# ...or this...
library(tidyverse)
list_of_scripts %>% 
  map(source)

我不了解文档,source()也无法删除详细输出。我尝试了 , , 等的各种组合echo = FALSEprint.eval = FALSEwithAutoPrint(print. = FALSE)控制台以列表结构打印$value$visible变量。

有没有办法抽象调用source()多个文件并保持“干净”的控制台输出?cat()如果输出可以自动插入换行符,那就更好了\n

标签: r

解决方案


另一种可能的选择:

file_path = "/path/to/dir"

现在列出您想要获取的所有 R 脚本:

r_scritps_source = list.files(file_path, recursive = T, full.names = T, pattern = ".R")

现在:

invisible(lapply(r_scripts_source, source))

或更紧凑:

invisible(lapply(list.files(file_path, recursive = T, full.names = T, pattern = ".R"), source))

推荐阅读