3

I am trying to write a series of characters and numerical values using sprintf and sink:

 sink("sample.txt", append=TRUE, split=TRUE)
 sprintf("Hello World")

of course, the above is an example, so I don't have the numerical values from a data frame above, but I need to use sprintf.

The output in the text file (sample.txt) looks like this:

 [1] Hello World

How do I remove the [1] from the line? Is there a way so the [1] won't write to the file?

Sheila
  • 2,438
  • 7
  • 28
  • 37

1 Answers1

6

Two options spring to mind, using cat() or writeLines()

> cat(sprintf("Hello World"), "\n")
Hello World 
> writeLines(sprintf("Hello World"))
Hello World

The problem you have is that sprintf() returns a character vector and like any other character vector R prints it like a vector if you print it. What you want is the string contained with the first element of the character vector (the only one in this case). Hence we use tools to write out the string not print the character vector.

Note that both these can write directly to a file via the file argument (in cat()) or the con argument (in writeLines()), which you may find useful.

Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
  • Thanks for your explanation! I used cat() and that worked great. – Sheila Jul 22 '13 at 22:26
  • Can this be changed in the default settings (to the effect of always using `cat`, but without actually using it) ? – Rich Scriven Mar 20 '14 at 08:03
  • @RScriv I would write a wrapper to `sprintf()` (say `wrapSprintf()`) that returned the character vector with class `c("foo","character")`, then write a `print.foo()` method which called `cat()` or `writeLines()`. With those two in place, you could do `wrapSprintf("whatever")` and the S3 dispatch & auto-printing would do the rest. This is slightly abusing the `print` system, but is more in line with having a tool do one thing - return character - & another tool to display that character vector in particular way. – Gavin Simpson Mar 20 '14 at 15:18