0

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!

Community
  • 1
  • 1
inDoze
  • 11
  • 1
  • 5

3 Answers3

10

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")
Ricardo Saporta
  • 54,400
  • 17
  • 144
  • 178
2

In addition to using paste instead of cat, you could also possibly use cat directly in place of writeLines with the file argument to cat pointing to the connection. Or even less work (for the programmer, not the computer) is to not worry about the connection yourself but use the file and append arguments to cat to add to a file.

Greg Snow
  • 48,497
  • 6
  • 83
  • 110
1

Try substituting the "cat" function for the "paste" function:

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)
leobarone
  • 46
  • 3