r - 读入部分文件名发生变化的文件
问题描述
我有一些文件名,如下所示;
第一年:
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)
解决方案
推荐阅读
- python - 如何使用“and”运算符加入列表中的每个项目
- python - 我有一些代码,我想对它进行一些故障排除
- javascript - VS Code 函数转到下一个空间
- javascript - 点击事件在 iPad 上不起作用,但在桌面和移动设备上起作用
- python - 无法保持定义的变量
- vbscript - 使用带有 setRequestHeader 的变量,为什么它们不起作用?
- python - 我想分析捕获的数据包,但代码给出错误
- flutter - 发回数据后列表视图不会更新(颤振)
- reactjs - 确保打印时反应组件不被分解
- google-app-engine - 查找返回空数据集的数据库中的记录的方法