我有一组 67 个 Excel 文件,我正在尝试将其合并到 R 中的面板数据集中。文件名的形式为:qjMMMYYe.xls
,其中MMM
是月份的三个字母缩写,以两个月为增量从jan
到nov
,YY
是年份,从09
到20
运行。第一个是qjjan09e.xls
,最后一个是qjjan20e.xls
.
我是 R 的新手,我想:
a) 将每个文件读入 R 并以可以按时间顺序排序的方式命名,例如qjjan09e.xls
分配给data0901
,qjjan20e.xls
分配给data2001
b) 在每个数据帧中创建三个新列:year
和month
存储各自的日期组件,wave
存储文件的时间顺序编号(例如,第一个文件qjjan09e.xls
被分配1
,最后一个文件qjjan20e.xls
被分配67
c) 将数据帧堆叠在一起以创建面板数据集
对于a),我通过list.files(pattern="*.xls")
获取文件名列表并通过循环读取read_excel
,但我无法弄清楚如何使用正则表达式重命名数据帧。我认为如果我能找到一种方法从文件名中提取三个字母的缩写,month.abb
函数将对我有所帮助。我假设这部分可以帮助我创建 b 中所需的年份和月份列),但我也不确定如何从重命名的文件中获取波号。我假设c)涉及rbind()
.
我的解决方案涉及tidyverse
(用于一些可读的数据争用),data.table
用于快速处理大量数据
这可能不是最优雅的方式,但它会完成工作;-)
我在下面的代码中包含了注释和结果
library( tidyverse )
library( readxl )
library( data.table )
#get files to read
files.v <- list.files( path = "./temp", pattern = ".*\.xls$", full.names = TRUE )
# [1] "./temp/qjjan09e.xls" "./temp/qjjan20e.xls"
#build df for lookup operation later on
DF <- data.frame( filename = files.v ) %>%
dplyr::mutate(
#use rownumbers to get file identifier
id = row_number(),
#extract year and month string from filename, and parse to date
date_id = paste0( gsub( "^.*([a-z]{3})([0-9]+.*)", "\1", filename ),
gsub( "[^0-9]", "", filename ) ) %>%
#parse extracted strings to 'real' date using the corerect locale
readr::parse_date( format = "%b%y", locale = locale( date_names = "en" ) ) %>%
#format the date to the desired format
format( "%y%m" )
)
# filename id date_id
# 1 ./temp/qjjan09e.xls 1 0901
# 2 ./temp/qjjan20e.xls 2 2001
#read excel-files to list
L <- lapply( files.v, readxl::read_excel )
#name list
names(L) <- files.v
# $`./temp/qjjan09e.xls`
# # A tibble: 5 x 2
# col1 col2
# <dbl> <dbl>
# 1 1 8
# 2 2 9
# 3 3 10
# 4 4 11
# 5 5 12
#
# $`./temp/qjjan20e.xls`
# # A tibble: 5 x 2
# col1 col2
# <dbl> <dbl>
# 1 11 18
# 2 12 19
# 3 13 20
# 4 14 21
# 5 15 22
#now bind the List together, using it's names as an ID
DT <- data.table::rbindlist( L, use.names = TRUE, fill = TRUE, idcol = "filename" )
# filename col1 col2
# 1: ./temp/qjjan09e.xls 1 8
# 2: ./temp/qjjan09e.xls 2 9
# 3: ./temp/qjjan09e.xls 3 10
# 4: ./temp/qjjan09e.xls 4 11
# 5: ./temp/qjjan09e.xls 5 12
# 6: ./temp/qjjan20e.xls 11 18
# 7: ./temp/qjjan20e.xls 12 19
# 8: ./temp/qjjan20e.xls 13 20
# 9: ./temp/qjjan20e.xls 14 21
#10: ./temp/qjjan20e.xls 15 22
#now join the relevant info into the coluns needed, using a (fast!!) update join
# setDT is used on DF to make it a data.table
DT[ data.table::setDT(DF),
`:=`( id_col = i.id, date_col = i.date_id ),
on = .( filename )]
# filename col1 col2 id_col date_col
# 1: ./temp/qjjan09e.xls 1 8 1 0901
# 2: ./temp/qjjan09e.xls 2 9 1 0901
# 3: ./temp/qjjan09e.xls 3 10 1 0901
# 4: ./temp/qjjan09e.xls 4 11 1 0901
# 5: ./temp/qjjan09e.xls 5 12 1 0901
# 6: ./temp/qjjan20e.xls 11 18 2 2001
# 7: ./temp/qjjan20e.xls 12 19 2 2001
# 8: ./temp/qjjan20e.xls 13 20 2 2001
# 9: ./temp/qjjan20e.xls 14 21 2 2001
#10: ./temp/qjjan20e.xls 15 22 2 2001