首页 > 解决方案 > 读入部分文件名发生变化的文件

问题描述

我有一些文件名,如下所示;

第一年:

blds_PANEL_DPK_8237_8283
blds_PANEL_DPR_8237_8283
blds_PANEL_MWK_8237_8283

它们都位于同一文件路径中。但是,在不同年份的不同文件路径中,我有非常相似的文件;

第 2 年:

blds_PANEL_MHG_9817_9876
blds_PANEL_HKG_9817_9876
blds_PANEL_DPR_9817_9876

有些文件的名称与前几年相同,但有些名称发生了变化。名称中唯一改变的部分是名称的MHG, HKG,DPR部分,与blds_PANEL_保持相同9817_9876

我创建了一个paste0()

file_path = C:/Users...
product = blds
part_which_keeps_changing = HKG
weeks = 9817_9876

read.csv(paste0(file_path, product, product, part_which_keeps_changing, weeks, ".DAT"), header = TRUE)

它对一种产品运行良好,但是对于新产品,我遇到了一些错误。所以我试图加载可能忽略这部分文件名的数据。

编辑:这似乎解决了我想要做的事情

temp <- list.files(paste0(files, product), pattern = "*.DAT")

location <- paste0(files, product, temp)

myfiles = lapply(location, read.csv)

library(plyr)
df <- ldply(myfiles, data.frame)

对于某些文件,我如何遇到稍微不同的问题。

如果我有以下情况;

blds_PANEL_DPK_8237_8283
blds_PANEL_DPR_8237_8283
blds_PANEL_MWK_8237_8283

其中一个文件可能不包含任何信息,当我应用lapply它时,它会在加载数据时中断并停止加载数据。

是否可以跳过这些文件。继承人的错误:

Error in read.table(file = file, header = header, sep = sep, quote = quote,  : 
  no lines available in input

编辑2:

这似乎覆盖了lapply错误:

lapply_with_error <- function(X,FUN,...){    
  lapply(X, function(x, ...) tryCatch(FUN(x, ...),
                                      error=function(e) NULL))
}

myfiles = lapply_with_error(location, read.delim)

标签: r

解决方案


推荐阅读