tags:

views:

37

answers:

2

Hi All,

I have the following R code:

df <- xmlToDataFrame(/Users/usr/Desktop/shares.xml)
df$timeStamp <- strptime(as.character(df$XTimeStamp), "%H:%M:%OS")
df$SharePrice <- as.numeric(as.character(df$SharePrice))
sapply(df, class)
options("digits.secs"=3)
diff <- diff(df$SharePrice)
diff
sink (file="c:/xampp/htdocs/data.xml", type="output",split=FALSE)
cat("<graph caption=\"Share Price Data Wave\" subcaption=\"For Company's Name\"    xAxisName=\"Time\" yAxisMinValue=\"0\" yAxisName=\"Price\" decimalPrecision=\"5\" formatNumberScale=\"0\" numberPrefix=\"\" showNames=\"1\" showValues=\"0\" showAlternateHGridColor=\"1\" AlternateHGridColor=\"ff5904\" divLineColor=\"ff5904\" divLineAlpha=\"20\" alternateHGridAlpha=\"5\">\n")
cat(sprintf("    <set name=\"%s\" value=\"%f\" hoverText = \"The difference from last value = %d\" ></set>\n", df$XTimeStamp, df$SharePrice, diff))

I am creating a new xml file in a format that FusionChart Free can read and I am trying to put the message in the hoverText area. However, when I run the commands I get the following error:

Error in sprintf("    <set name=\"%s\" value=\"%f\" hoverText = \"The difference from last value = %d\" ></set>\n",  : 
 arguments cannot be recycled to the same length

When I view the diff it has one less diff than SharePrice (obviously because the difference from point 1 to point 1 is zero), so how can account for this in the sprint function (It produces the correct format xml file if I leave out the diff)?

+2  A: 

Either get rid of the first element of df$XTimeStamp and df$SharePrice or add a NA as the first element of diff.

cat(sprintf("    <set name=\"%s\" value=\"%f\" hoverText = \"The difference from last value = %d\" ></set>\n", df$XTimeStamp[-1], df$SharePrice[-1], diff))

or

cat(sprintf("    <set name=\"%s\" value=\"%f\" hoverText = \"The difference from last value = %d\" ></set>\n", df$XTimeStamp, df$SharePrice, c(NA,diff)))
Joshua Ulrich
diff (a) always has one less element than a. Therefore, the way to go is to add an NA first element.
Anthony Keane
A: 

Also, if you are doing a lot of this kind of template-filling, look at the 'brew' package on CRAN - nothing to do with your original question but whenever I see an ugly-looking long sequence of 'cat' function calls I just have to mention it.

Spacedman