Reputation: 21
I am trying to write multiple lines in a txt by changing a different value every time and create a new file for each change. My code looks like this:
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
}
}
Now the problem is the writelines command, it should only contain one text and then the filename. But how do I write x and m in the same file and save it as a new file?
Kind Regards, André
Upvotes: 2
Views: 1662
Reputation: 1492
Try this:
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)
Where Line1 and Line2 are your first two lines. You can put more in by just adding to this vector (ie c(Line1, Line2, Line3)
Upvotes: 2