【问题标题】:Loop: Convert many .txt to .csv in single directory [Using R]循环:在单个目录中将许多 .txt 转换为 .csv [使用 R]
【发布时间】:2016-10-18 05:56:15
【问题描述】:

可能是一个非常简单的答案,但我在循环中将一堆 .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"

格式都搞砸了。

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

干杯,谢谢。

【问题讨论】:

    标签: r loops csv dataframe


    【解决方案1】:

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

    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 的评论编辑书面文件名

    【讨论】:

    • 也许sub(pattern = "\\.txt$", replacement = ".csv", x = x) 而不是你的paste() 写的文件名。我们想删除旧的扩展名并用.csv 替换它而不插入空格。
    • 谢谢,改变了我的答案!
    • 感谢 Sumedh 和 Gregor!您的 cmets 组合完美。
    猜你喜欢
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 2019-10-07
    • 2021-06-05
    相关资源
    最近更新 更多