提取列表中的一部分字符串以填充表

时间:2019-07-09 11:40:40

标签: r dplyr tidyverse

我一直试图编写一个从文件夹中多个Excel文件读取的代码,该文件与名称匹配。我已经可以使用显示一些代码的代码来实现这一部分。数据框中的列是id和Date。

我的问题是我想添加另一个名为Code的列,该列将保存从文件列表中提取的代码以区分每一行。

重新整理文件并合并该数据集后的初始数据帧

id                          Date              
    ExcelFile/CP1213_.xlsx  2013-05-09        
    ExcelFile/CP1213_.xlsx  2013-01-30      
    ExcelFile/CP1314_.xlsx  2013-02-14        
    ExcelFile/CP1314_.xlsx  2013-03-19        
    ExcelFile/CP1415_.xlsx  2013-02-22      
    ExcelFile/CP1415_.xlsx  2013-02-22      

下表显示了我要实现的目标:

id                          Date            Code   
ExcelFile/CP1213_.xlsx      2013-05-09      CP1213  
ExcelFile/CP1213_.xlsx      2013-01-30      CP1213
ExcelFile/CP1314_.xlsx      2013-02-14      CP1314  
ExcelFile/CP1314_.xlsx      2013-03-19      CP1314  
ExcelFile/CP1415_.xlsx      2013-02-22      CP1415 
ExcelFile/CP1415_.xlsx      2013-02-22      CP1415

文件的输出是一个列表:“ ExcelFile / CP1213_.xlsx”“ ExcelFile / CP1314_.xlsx”“ ExcelFile / CP1415_.xlsx”

files <- list.files(path = "ExcelFile/", pattern   = "*.xlsx", full.names = T)



tbl <- sapply(files, read_excel, simplify=FALSE) %>% bind_rows(.id = "id") 

2 个答案:

答案 0 :(得分:1)

根据罗纳克·沙阿(Ronak Shah)的想法,您可以使用dplyr软件包中的 mutate ,然后使用 basename ,然后使用 sub 提取部分文件名。来自ID的strong>。

files <- list.files(path = "ExcelFile/", pattern   = "*.xlsx", full.names = T)

tbl <- sapply(files, read_excel, simplify=FALSE) %>% bind_rows(.id = "id")

tbl <- tbl %>% mutate(Code = sub("_.*", "", basename(tbl$id)))

答案 1 :(得分:0)

您可以使用basename,然后使用sub

提取部分文件名。
df$Code <- sub("_.*", "", basename(as.character(df$id)))

df
#                      id       Date   Code
#1 ExcelFile/CP1213_.xlsx 2013-05-09 CP1213
#2 ExcelFile/CP1213_.xlsx 2013-01-30 CP1213
#3 ExcelFile/CP1314_.xlsx 2013-02-14 CP1314
#4 ExcelFile/CP1314_.xlsx 2013-03-19 CP1314
#5 ExcelFile/CP1415_.xlsx 2013-02-22 CP1415
#6 ExcelFile/CP1415_.xlsx 2013-02-22 CP1415

或者如果您要从files提取它

df$Code <- sub("_.*", "", basename(files))