Anthony Keane Anthony Keane - 1 year ago 117
R Question

How to print R variables in middle of String

I am trying to print out a line that contains a mixture of a String and a variable. Here is the R code at present:

cat("<set name=\",df$timeStamp,\" value=\",df$Price,\" ></set>\n")

Here is what it prints out when run:

<set name=",df$timeStamp," value=",df$Price," ></set>

I would like it to have the value of df$timeStamp and df$Price printed out. I would like for example the following:

<set name="2010-08-18 12:00:59" value="17.56" ></set>

Any idea where I am going wrong in the code?

Any and all help greatly appreciated.



Answer Source

The problem is that R does not evaluate any expression withing the quotes - it is just printing the string you defined. There are multiple ways around it. For example, you can use the sprintf function (untested because you do not provide a reproducible example):

   cat(sprintf("<set name=\"%s\" value=\"%f\" ></set>\n", df$timeStamp, df$Price))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download