Reputation: 2176
Im trying to loop through a data frame to produce a text file with a specific format. Here is an example data frame:
x <- 1:10
y <- 10:1
df <- data.frame(x,y)
This loop will print text in the format I want it:
for (n in 1 : length(df[,1]))
{
cat(paste("\n-insertblock weld\n", df[n,1], df[n,2], "\n1\n1\n0", sep = " "))
}
I would now like to do two things: 1) add the print to a txt file 2) add some more text to the top (will be the same for every file i produce). I have found this question which shows how to write txt to a file:
Write lines of text to a file in R
And this one (how to write to files with writeLines in R) tells me that writeLines
needs things to be as.character
. This is my attempt:
fileConn <- file("output.txt")
for (n in 1 : length(df[,1]))
{
writeLines(cat(paste("\n-insertblock weld\n", as.character(df[n,1])), as.character(df[n,2]), "\n1\n1\n0", sep = " "), fileConn)
}
close(fileConn)
However, this gives an error:
Error in writeLines(cat(paste("\n-insertblock weld\n", as.character(df[n, : invalid 'text' argument
If I remove cat
the error goes away but I only get the last line of the output:
for (n in 1 : length(df[,1]))
{
writeLines(paste("\n-insertblock weld\n", as.character(df[n,1]), as.character(df[n,2]), "\n1\n1\n0", sep = " "), fileConn)
}
close(fileConn)
-insertblock weld
10 1
1
1
0
After I have created the correct txt file I need to add this to the top:
--simplenote
J
C
-36.413,33.568
5
0
Am i barking up the wrong tree with my method for saving the pasted text? Any help appreciated
Upvotes: 3
Views: 2897
Reputation: 5169
sink("count.txt",split=FALSE,append = FALSE)
cat(paste("--simplenote\n","J\n","C\n","-36.413,33.568\n","5\n","0\n", sep = " "))
for (n in 1 : length(df[,1]))
{
cat(paste("\n-insertblock weld\n", df[n,1], df[n,2], "\n1\n1\n0", sep = " "))
}
Upvotes: 2