【问题标题】:parameter not passed to the function when using walk function in PURRR package在 PURRR 包中使用 walk 函数时参数未传递给函数
【发布时间】:2021-01-11 03:41:03
【问题描述】:

我正在使用 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文件。如何动态分配数据集名称?

【问题讨论】:

    标签: r tidyverse purrr


    【解决方案1】:

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

    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)
    

    【讨论】:

    • 非常感谢您的回复。我还有一个问题。对象“结果”是一个列表,其中每个元素都包含一个小标题。如何将对象结果转换为小标题?我可以使用result2=rbind(result[[1]],result[[2]]),但是元素个数可能不固定。
    • 您可以使用map_df将它们组合成一个数据框,即result &lt;- purrr::map_df(files,file_read)
    猜你喜欢
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    • 2015-07-22
    • 2022-01-25
    • 2013-01-27
    • 2011-06-12
    • 1970-01-01
    • 2020-08-19
    相关资源
    最近更新 更多