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

布赖恩·加尔

我有8个没有标题的文本文件,我的目标是全部读取它们并将它们组合成一个文件。我也想添加列名,但不断出现错误。到目前为止,我的代码是:

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")

我一直收到此错误:names(x)<-value中的错误:'names'属性[19]的长度必须与向量[1]的长度相同

但是我知道这些都是专栏,它们是相同的。

我还试图在列中指定文本文件的来源ID,但这是一个单独的问题。谢谢任何看到这个的人

你好朋友

尝试这个:

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")) 

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

TOP 榜单

热门标签

归档