如何在 R 中导入多个 txt 文件并添加新的 header?

How to import multiple txt files in R and add new header?

我有 8 个文本文件,没有 headers 全部保存,我的目标是将它们全部读入并将它们合并到一个文件中。我还想添加列名,但一直出错。到目前为止我的代码是:

txt_files_ls = list.files(path=mypath, pattern="*.txt")


txt_files_df <- lapply(txt_files_ls, function(x) {read.table(file = x, header = F, sep ="\t",colnames(x))})


combined_df <- do.call("rbind", lapply(txt_files_df, as.data.frame)) 

colnames(combined_df)<-c("INSUR","POLICY","STREET","STREETPRED","STREETNAME","STREETTYPE","STREETPOSTD","STREETADD2","CITY","STATE","ZIP","ZIP4","EFFDATE","POLTYPE","PREM","FILL", "BVAMOUNT","Full","COUNT")

我不断收到此错误:名称错误 (x) <- 值: 'names' 属性 [19] 必须与向量 [1]

的长度相同

但我知道这些都是列并且它们是相同的。

我也想有一个列来标识文本文件的来源,但这是一个单独的问题。 感谢任何看到此内容的人

试试这个:

txt_files_ls <- paste(mypath, list.files(path = mypath, pattern = "*.txt"), sep = "/")
txt_files_df_list <- vector("list", length(txt_files_ls))
txt_files_df_list <- lapply(txt_files_ls, 
                       function(x){data.frame(read.table(file = x, header = F,
                                                         sep ="\t",colnames(x)))})
combined_df <- setNames(do.call("rbind", txt_files_df_list),
                        c("INSUR", "POLICY","STREET","STREETPRED","STREETNAME",
                          "STREETTYPE","STREETPOSTD","STREETADD2","CITY","STATE",
                          "ZIP","ZIP4","EFFDATE","POLTYPE","PREM","FILL", "BVAMOUNT",
                          "Full","COUNT"))