创建循环:在R中将.txt转换为.csv [英] create a loop: convert .txt to .csv in R

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

问题描述

我尝试将所有.txt文件转换为.csv,但是我没有设法创建循环. 一个文件的实际行(完美运行)如下:

I try to convert all my .txt files in .csv, but I didn't manage to create the loop. The actual line for one file (which works perfectly) would be the following:

tab = read.delim("name_file", header = TRUE, skip = 11)
write.table(tab, file="name_file.csv",sep=",",col.names=TRUE,row.names=FALSE)

我想对wd中的所有.txt文件执行此操作.

And I would like to do that for all the .txt file I have in wd.

基于网络上的一些研究,我尝试了循环,但是我不确定这是正确的方法:

I tried the loop with, based on some reasearch on the web, but I am not sure it's the right one:

FILES = list.files(pattern = ".txt")
for (i in 1:length(FILES)) {
  FILES = read.csv(file = FILES[i], header = TRUE, skip = 11, fill = TRUE)
  write.csv(FILES, file = paste0(sub("folder_name", ".txt","", FILES[i]), ".csv"))
}

我在Windows系统上. 我会感谢您的帮助...谢谢!

I'm on Windows system. I would appreciate some help... Thanks!

推荐答案

像您一样,我也遇到了同样的问题,现在我使它起作用了.试试这个:

Hi I have the same problem before just like you, and now I made it works. Try this:

directory <- "put_your_txt_directory_here"
ndirectory <- "put_your_csv_directory_here"

file_name <- list.files(directory, pattern = ".txt")

files.to.read <- paste(directory, file_name, sep="/") 
files.to.write <- paste(ndirectory, paste0(sub(".txt","", file_name),".csv"), sep="/")

for (i in 1:length(files.to.read)) {
  temp <- (read.csv(files.to.read[i], header = TRUE, skip = 11, fill = TRUE))
  write.csv(temp, file = files.to.write[i])
}

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

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