如何从文件夹加载多个文件并将部分文件名用作数据集中的列

How to load multiple files from a folder and use part of filename as column in dataset

感谢这样的论坛和博客,我正在慢慢摸索 R 并学到很多东西。 我找到了一段方便的代码(如下)来解决一个新问题的一部分,但现在我被卡住了。

library(readr)
library(dplyr)

myFiles <- list.files(path = "C:/Desktop/M2P/", pattern = "*.txt", full.names = FALSE)
myTable <- sapply(myFiles, read_csv, simplify=FALSE) %>% 
  bind_rows(.id = "id")

路径中的所有文件名都是这样的: 'YYYYMMDD_SUMMARY.txt'

该文件包含许多由“,”分隔的列

上面的代码向 table 添加了一个新列 ("id"),其中包含加载的确切文件名,以及我在列中的所有数据,这很棒,然而 ...

我想对此进行调整,以便添加一列,它只是文件名的日期部分,即 YYYY-MM-DD。 我想稍后使用这个日期来驱动一些功能并对数据进行分组。

这可能吗?

添加 mutate 语句以从文件名中获取日期。

library(dplyr)
library(readr)

sapply(myFiles, read_csv, simplify=FALSE) %>% 
   bind_rows(.id = "id") %>%
   mutate(id = sub('(\d+).*', '\1', id))
   #If you need as date object
   #mutate(id = lubridate::ymd(sub('(\d+).*', '\1', id)))

另一种方法是使用 tidyr 中的 separateid 拆分为日期和余数:

library(dplyr)
library(tidyr)

df <- tibble(id = c("20110101_SUMMARY", "20110201_SUMMARY", "20110301_SUMMARY"), x = runif(3), y = runif(3))
df %>% 
  separate(id, into = c("date", "desc")) %>% 
  mutate(date = as.Date(date, "%Y%m%d"))

这是一个 data.table 方法。由于您刚开始使用 R,它可能看起来有点吓人,但我强烈建议您看一下这个包...

解释和中间输出在下面的代码中注释..

--

假设我在子文件夹 "temp" 中有两个文件,如下所示:

内容如下:

#get a list of all *full* filenames in the folder ./temp, ending on the pattern ".txt" 
files.to.read <- list.files( path = "./temp", pattern = ".*.\.txt$", full.names = TRUE )
#[1] "./temp/20200302_SUMMARY.txt" "./temp/20200303_SUMMARY.txt"

#load data.table library
library( data.table )
#create a list, reading the files from the above created list
#fread() from the data.table package is a fast and robust reader, with many, many options.
l <- lapply( files.to.read, fread )
# [[1]]
# col1 col2
# 1:    6    9
# 
# [[2]]
# col1 col2
# 1:    1    4

#now, add names to the list, based on the read filenames 
#do this by removing all non digit-charactes (regex = "[^0-9]" ) from the filename (=basename)
names(l) <- gsub( "[^0-9]", "", basename(files.to.read) )

#as you can see, the dates are now the namse of the list l

# $`20200302`
# col1 col2
# 1:    6    9
# 
# $`20200303`
# col1 col2
# 1:    1    4

#now use rbindlist from the data.table package to rowbind the list together
#use the names from the list as id in a new column, named "date"
rbindlist( l, idcol = "date" )

最终输出

#        date col1 col2
# 1: 20200302    6    9
# 2: 20200303    1    4