问题描述
我有一组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
存储文件的时间顺序编号(例如第一个文件{{ 1}}被分配了qjjan09e.xls
,最后一个文件1
被分配了qjjan20e.xls
)
c)将数据框彼此堆叠以创建面板数据集
对于a),我通过67
获取文件名列表,并通过遍历list.files(pattern="*.xls")
来读取文件名,但是我不知道如何使用正则表达式重命名数据帧。我认为read_excel
函数可以帮助我,如果我能找到一种从文件名中提取三个字母缩写的方法。我认为这部分将帮助我创建b)中所需的年和月列,但是我也不确定如何从重命名的文件中获取波数。我假设c)涉及month.abb
。
解决方法
我的解决方案涉及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