tags:

views:

166

answers:

2

In the R scripting language, how do I write lines of text, e.g. the following two lines

Hello
World

to a file named "output.txt"?

+6  A: 
fileConn<-file("output.txt")
writeLines(c("Hello","World"), fileConn)
close(fileConn)
Mark
Thanks. I've been messing with sink() and message() for half an hour. This is way easier.
amarillion
Mark - what If I have several threads all of which I would like to add lines to the same file? (The issue being is that you can't have more then one connection to a file, If I am not mistaken)Thanks.
Tal Galili
@Tal, that is an excellent question, you should post it as a new, separate question so it'll get some attention. There are much more knowledgeable R programmers around here than me!
Mark
+2  A: 

Actually you can do it with sink():

> sink("outfile.txt")
> cat("hello")
> cat("\n")
> cat("world")
> sink()

hence do:

> file.show("outfile.txt")
hello
world
aL3xa
+1 even though now I feel extra dumb :P
amarillion
Now, don't be so hard on yourself... there are plenty of selfhandicaping moments in my R programming history! =)And @Mark's solution is pretty neat, so I recommend that you stick with it!
aL3xa