Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print R variables in middle of String

Tags:

r

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.

like image 765
Anthony Keane Avatar asked Aug 18 '10 19:08

Anthony Keane


People also ask

How do I print a variable in a string in R?

Print output using paste() function inside print() function R provides a method paste() to print output with string and variable together. This method defined inside the print() function. paste() converts its arguments to character strings. One can also use paste0() method.

How do I print multiple variables in one line in R?

You can use the cat() function to easily print multiple variables on the same line in R. This function uses the following basic syntax: cat(variable1, variable2, variable3, ...)

How do I make a variable into a string?

How to create a string and assign it to a variable. To create a string, put the sequence of characters inside either single quotes, double quotes, or triple quotes and then assign it to a variable.

How do I print text in R?

To display ( or print) a text with R, use either the R-command cat() or print(). Note that in each case, the text is considered by R as a script, so it should be in quotes. Note there is subtle difference between the two commands so type on your prompt help(cat) and help(print) to see the difference.


2 Answers

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)) 
like image 53
Aniko Avatar answered Oct 02 '22 15:10

Aniko


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") 
like image 21
Shane Avatar answered Oct 02 '22 15:10

Shane