将多个文件读入 R 后,如何将生成的 df 设置为文件名?

After reading multiple files into R, how can I set the resulting df's to the file name?

目前我正在使用下面的方法一次性将 ~7-10 个文件读入 R 控制台。

library(magrittr)
library(feather)

list.files("C:/path/to/files",pattern="\.feather$") %>% lapply(read_feather)

如何根据它们的唯一文件名将它们通过管道传输到独立的数据对象中?

例如

accounts_jan.feather
users_jan.feather
-> read feather function -> hold in working memory as:
accounts_jan_df
users_jan_df

谢谢。

这似乎是一个试图用管道做太多事情的案例 (https://github.com/hrbrmstr/rstudioconf2017/blob/master/presentation/writing-readable-code-with-pipes.key.pdf)。我建议稍微细分您的流程:

# Get vector of files
files <- list.files("C:/path/to/files", pattern = "\.feather$")

# Form object names
object_names <- 
  files %>%
  basename %>%
  file_path_sans_ext

# Read files and add to environment
lapply(files, 
       read_feather) %>%
  setNames(object_names) %>%
  list2env()

如果您真的必须使用单个管道执行此操作,您应该改用 mapply,因为它有一个 USE.NAMES 参数。

list.files("C:/path/to/files", pattern = "\feather$") %>%
  mapply(read_feather,
         .,
         USE.NAMES = TRUE,
         SIMPLIFY = FALSE) %>%
  setNames(names(.) %>% basename %>% tools::file_path_sans_ext) %>%
  list2env()

就我个人而言,当我进行调试时,我发现第一个选项更容易推理(我不喜欢管道中的管道)。