r-在PURRR包中使用walk函数时未传递给函数的参数



我正在使用purrr:walk读取多个excel文件,但它失败了。我有3个问题:

(1( 我使用函数list.files读取了一个文件夹中的excel文件列表。但是返回的值也包括子文件夹。我尝试为参数recursive=和include.dirs=设置值,但没有成功。

setwd(file_path)
files<-as_tibble(list.files(file_path,recursive=F,include.dirs=F)) %>%
filter(str_detect(value,".xlsx"))
files

(2( 当我使用以下代码时,它可以在没有任何错误或警告消息的情况下运行,但没有返回数据。

###read the excel data
file_read <- function(value1) {
print(value1)
file1<-read_excel(value1,sheet=1)
}
walk(files$value,file_read)

当我使用以下内容时,它起了作用。不知道为什么。

test<-read_excel(files$value,sheet=1)

(3( 在Q2中,实际上我想创建file1到file6,假设有6个excel文件。如何动态分配数据集名称?

list.filespattern参数,您可以在其中指定要查找的文件类型。这将帮助您避免filter(str_detect(value,".xlsx"))步骤。此外,除非指定recursive = TRUE,否则list.files只返回主目录(file_path(中包含的文件,而不返回其子目录。

library(readxl)
setwd(file_path)
files <- list.files(pattern = '\.xlsx')

在函数中,您需要return对象。

file_read <- function(value1) {
data <- read_excel(value1,sheet=1)
return(data)
}

现在您可以使用map/lapply来读取这些文件。

result <- purrr::map(files,file_read)

最新更新