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.
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.
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 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.
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.
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))
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With