R – Writing variables to a file with writeLines

r

I found this link very helpful in understanding how to write lines to a file: Write lines of text to a file in R

Unfortunately though I'm finding that I do not know how to use this line to write a variable to the text file. Does anybody know how to do this?

Here's a sampling of my script so you can see what I'm trying to do:

file.create(sample.txt)
fileConn <- file(sample.txt)
writeLines(c(cat(i, j, k, "07"),"1","41.6318 -87.0881   10.0"), fileConn)
close(fileConn)

My expectation was that this code would create my sample.txt file, connect to it, and write my cat(i, j, k, "07") as the first line (this cat statement corresponds to the date if you're curious), 1 to the second line, and the latitude, longitude, and elevation to the third line, and finally closes the file.

What gets output is the 1 on the first line and the Lat. and Lon. on the second line. The cat statement never makes it to the file. Is there something I can do about this? Is a cat statement within a writeLines statement not the best way to go about this? Any help you can give is appreciated. Thank you!

Best Solution

Use paste instead of cat

file.create("sample.txt")
fileConn <- file("sample.txt")
writeLines(c(paste(i, j, k, "07"),"1","41.6318 -87.0881   10.0"), fileConn)
close(fileConn)
file.show("sample.txt")
Related Question