user2543622
user2543622

Reputation: 6756

writing output to a text file R

I have below code. It works fine.

  1. But i want to write the text within square braces - ["gaugeid" : "gauge1234",] to a line in the file. How can I do that?
  2. I also want to write the text within square braces to a line - ["abc" : 5,] where 5 in actual value of variable abc. How could I do that?

I am confused as my line starts with " and ends with '

abc=5
sink("output.txt")
cat("\n")
cat("abc : ")
#cat(""gaugeid" : "gauge1234",")
sink()

Upvotes: 0

Views: 309

Answers (2)

IRTFM
IRTFM

Reputation: 263331

You cannot have naked double-quotes in an R string unless is surrounded by single quotes.

> cat('"gaugeid" : "gauge1234",')
"gaugeid" : "gauge1234",

Or you can escape the double quotes inside your original effort:

> cat("\"gaugeid\" : \"gauge1234\",")
"gaugeid" : "gauge1234",

For the second question is as simple as adding a comma and the variable name which will hten be evaluated before writing to the output device:

> cat("abc : ", abc)
abc :  5

Upvotes: 1

Dave2e
Dave2e

Reputation: 24069

Try:

abc=5
sink("output.txt")
cat("\n")
cat("abc : ")
cat(abc)
cat(",")
sink()

The first cat("abc") is adding the string abc, while the second cat(abc) is adding the variable abc to the output file.

Upvotes: 1

Related Questions