使用R将多行写入txt文件

时间:2014-05-05 13:52:47

标签: r

我试图通过每次更改不同的值来在txt中写入多行,并为每次更改创建一个新文件。 我的代码如下所示:

setwd("c:\\Andre\\")#set the working directory
parameter <- read.csv("Parameter_Distribution.csv",header=TRUE)
FSTDEC <- parameter$FSTDEC #the FSTDEC parameter from the table
KBOD20 <- parameter$KBOD20
x <- readLines("1.txt")
m <- readLines("1.txt")

for(y in 1:length(KBOD20))
{
  for(i in 1:length(FSTDEC))
{
  regexp <- "KBOD20"
  Lineno <- grep(pattern = regexp, x = x , value = F) #find the place that have the parameter
  newline1 <- paste("    1    3     ",KBOD20[y],"         1     0.101      1.15",sep='')#the newline for the replacement
  m[Lineno+2] <- newline1 
  regexp <- "FSTDEC"
  Lineno <- grep(pattern = regexp, x = x , value = F)
  newline1 <- paste("    1   17      ",FSTDEC[i],"         1",sep='')
  x[Lineno+2] <- newline1

filename <- paste("Newfiles\\FSTDEC@",FSTDEC[i],".UCI",sep='')
  writelines(x,m,filename) #generate the file with the new file name
  }
}

现在问题是writelines命令,它应该只包含一个文本,然后是文件名。 但是如何在同一个文件中编写x和m并将其另存为新文件?

亲切的问候, 安德烈

1 个答案:

答案 0 :(得分:1)

试试这个:

 Line1 = "Line One of Text File"
 Line2 = "The Second Line of the Text File"

FileName = "TextFile.txt"

fileConn<-file(FileName)
writeLines(c(Line1, Line2), fileConn)
close(fileConn)

Line1和Line2是前两行。只需添加到此向量(即c(Line1,Line2,Line3)

即可添加更多内容