【问题标题】:Help with sprintf function in R帮助 R 中的 sprintf 函数
【发布时间】:2010-08-25 22:23:08
【问题描述】:

我有以下 R 代码:

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))

我正在以 FusionChart Free 可以读取的格式创建一个新的 xml 文件,并且我正在尝试将消息放在 hoverText 区域中。但是,当我运行命令时,出现以下错误:

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

当我查看差异时,它的差异比 SharePrice 少一个(显然是因为从点 1 到点 1 的差异为零),所以如何在 sprint 函数中解释这一点(如果我会生成正确格式的 xml 文件忽略差异)?

【问题讨论】:

    标签: r printf


    【解决方案1】:

    要么去掉df$XTimeStampdf$SharePrice的第一个元素,要么添加一个NA作为diff的第一个元素。

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

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

    【讨论】:

    • diff (a) 总是比 a 少一个元素。因此,要走的路是添加一个 NA 第一个元素。
    【解决方案2】:

    另外,如果您正在做很多此类模板填充,请查看 CRAN 上的“brew”包 - 与您的原始问题无关,但每当我看到一个看起来难看的长序列“猫”时函数调用我不得不提一下。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-06
      • 1970-01-01
      • 2014-05-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多