How to print R variables in middle of String

Viewed 102156

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.

Regards,

Anthony.

4 Answers

There is now a very convenient function to perform string formatting that works pretty much like Python f-strings. str_glue is part of the stringr package.

library(stringr)

str_glue('<set name="{df$timeStamp}" value="{df$Price}"></set>')

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