循环:在单个目录中将许多.txt转换为.csv [使用R]

时间:2016-06-16 15:50:07

标签: r loops csv dataframe

可能是一个非常简单的答案但我在循环中将一堆.txt文件转换为.csv文件时遇到了麻烦。我不想合并或追加它们,只需将71个单独的.txt文件转换为71个单独的.csv文件。

我正在尽力使用依赖于此主题的代码来引用其他问题: create a loop: convert .txt to .csv in R

我正在调整它,这是我到目前为止所做的:

filelist = list.files(pattern = ".txt")

 for (i in 1:length(filelist)) {
  cur.input.file <- filelist[i]
  cur.output.file <- paste0(cur.input.file, ".csv") 
  print(paste("Processing the file:", cur.input.file))

  # If the input file has less than 11 rows you will reveive the error message:
  # "Error in read.table: no lines available in input")
  data = read.delim(cur.input.file, header = TRUE)
  write.table(data, file=cur.output.file, sep=",", col.names=TRUE, row.names=FALSE)
}

然而,我的结果是:

[1] "Processing the file: filename1.txt.txt"
[1] "Processing the file: filename2.txt.txt"
[1] "Processing the file: filename3.txt.txt"
[1] "Processing the file: filename4.txt.txt"
[1] "Processing the file: filename5.txt.txt"

并且格式化都搞砸了。

任何建议/我做错了什么?

干杯谢谢。

1 个答案:

答案 0 :(得分:2)

这是一个基本的解决方案:

filelist <- list.files(pattern = ".txt")
someVar <- lapply(filelist, function(x) { 
                            textfile <- read.table(x)
                            write.csv(textfile, 
                       file = sub(pattern = "\\.txt$", replacement = ".csv", x = x))
 })

您始终可以根据您的要求在read.table和write.csv函数中添加参数。

根据Gregor的评论编辑的文件名