如何遍历 R 脚本中的文件名? [英] How to iterate over file names in a R script?

查看:33
本文介绍了如何遍历 R 脚本中的文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个非常简单的 R 脚本向文本文件0.txt"添加了一个升序行索引,并为其添加了一个标题时间".之后将数据写入文件0-edit.txt"

A very simple R script adds a ascending row index to a textfile "0.txt" and also adds a header "time" to it. After that the data is written to a file "0-edit.txt"

data<-read.table("0.txt", header=TRUE,sep=",",row.names= NULL);
colnames(data)[1] = "time"
write.table(data,quote=FALSE,sep=", ","0-edit.txt");

假设我在同一个文件夹中有 4 个文件,分别称为 0.txt、1.txt、2.txt...,我如何使用计数器(或其他东西)在脚本中迭代这些文件名?

Assume i have 4 files called 0.txt, 1.txt, 2.txt, ...in the same folder, how can I use a counter (or something else) to iterate over those file names in my script?

推荐答案

for(i in 0:3) {
  infile <- paste(i,".txt",sep="")
  outfile <- paste(i,"-edit.txt",sep="")

  data <- read.table(infile,header=TRUE,sep=",",row.names=NULL)
  colnames(data)[1] = "time"
  write.table(data,quote=FALSE,sep=", ",outfile)
}

这篇关于如何遍历 R 脚本中的文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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