循环:在单个目录中将许多.txt转换为.csv [使用R] [英] Loop: Convert many .txt to .csv in single directory [Using R]

查看:114
本文介绍了循环:在单个目录中将许多.txt转换为.csv [使用R]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Probably a pretty simple answer but I've had trouble converting a bunch of .txt files to .csv files in a loop. I don't want to merge or append them, just convert 71 individual .txt files into 71 individual .csv files.

我正在尽最大努力参考我依赖此线程的代码中的其他问题: 创建循环:在R中将.txt转换为.csv

I was doing my best to refer to other questions with my code relying on this thread: create a loop: convert .txt to .csv in R

我正在对其进行调整,这是我到目前为止所掌握的:

I was adapting it and this is what I have so far:

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"

所有格式都搞砸了.

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

Any advice/ what am I doing wrong?

干杯,谢谢.

推荐答案

这是一个基本解决方案:

This is a basic solution:

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函数中添加参数.

You can always add parameters in the read.table and write.csv functions per your requirements.

根据Gregor的注释编辑的书面文件名

Edited written file name per Gregor's comment

这篇关于循环:在单个目录中将许多.txt转换为.csv [使用R]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆