33

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.

Anthony Keane
  • 821
  • 3
  • 12
  • 17

4 Answers4

24

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))
Aniko
  • 18,516
  • 4
  • 48
  • 45
  • 3
    When using single quotes, this makes the whole thing easier to read... `cat(sprintf('\n', df$timeStamp, df$Price))` – drmariod Sep 19 '16 at 15:19
16

You're missing some extra quotes. Try this:

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

Here's a working example of what I mean:

cat("a b c -> \"", letters[1:3], "\"\n")
Shane
  • 98,550
  • 35
  • 224
  • 217
  • 13
    If you want to be super-slick, you can avoid having to escape quotes (in this case) by using single-quotes to delineate the string and double-quotes within it: `cat('a b c -> "', letters[1:3], '"\n')` – Joshua Ulrich Aug 18 '10 at 19:54
8

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>
Romain
  • 19,910
  • 6
  • 56
  • 65
3

Cat works just fine without extra libraries and escapes:

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

output:

<set name="2010-08-18 12:00:59" value="17.56"></set>
  • This is nearly identical to Shane's answer. The addition of the `sep` argument should probably be a comment on his answer rather than a new post. – Matthew Lundberg Sep 19 '16 at 18:37