0

I'm trying to create a data file (data.file).

I have a string: string=c("test1","test2","test3") which I need to combine with some other commands and write to a text file. string can be of any length.

In this specific case, the output I want in my data file is: : "test1" "test2" "test3" :=

I tried cat(':',string,':=\n',file=data.file,append=TRUE) but this isn't returning the quotation marks that I need.

(It returns : test1 test2 test3 := which is missing the quotation marks) .

How could I do this? And, can it also be done with writeLines?

James
  • 309
  • 1
  • 10

1 Answers1

1

writeLines literally just writes lines separated by line separators, nothing more. Formatting has to be done before that.

In order to surround your text by quotes, you can simply do the following:

sprintf('"%s"', string)

sprintf is a versatile text formatting function (although its usage is quite arcane).

However, there’s a problem if your strings can contain quotation marks. What should happen in such a case? In general, one has to pay close attention to what values are allowed for string content before formatting it, and how to deal with unexpected input.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 1
    So something like this: `writeLines(c(":",sprintf('"%s"', string),":="),con=data.file)` ? – James Jan 15 '15 at 12:54
  • @James Yes, that would work (but the elements would be on separate lines, unless you set the parameter `sep` to some other value). You can equally use `cat` instead of `writeLines`. Then you don’t need to put the arguments into a vector (so leave off `c(`…`)`). – Konrad Rudolph Jan 15 '15 at 13:01