在Rmarkdown

时间:2016-01-25 14:37:09

标签: r r-markdown

我尝试使用rmarkdown撰写简短报告,我希望使用getSymbolds包的quantmod函数从雅虎下载市场数据。

---
title: "TEST"
author: "TEST"
date: "Monday, January 25, 2016"
output: html_document
---
```{r, echo=FALSE}
require(quantmod)
prices = invisible(getSymbols("^GDAXI", return.class = "xts", auto.assign=FALSE ))
cat(getwd())
rets = na.omit(diff(log(prices[,4]))) - mean(na.omit(diff(log(prices[,4]))))
plot(rets['2015/2016'])
```

但是,调用prices = invisible(getSymbols("^GDAXI", return.class = "xts", auto.assign=FALSE ))不起作用,我收到错误消息:

Quitting from lines 8-13 (Preview-1a04527111.Rmd) 
Error in download.file(paste(yahoo.URL, "s=", Symbols.name, "&a=", from.m,  : 
  cannot open URL 'http://ichart.finance.yahoo.com/table.csv?s=^GDAXI&a=0&b=01&c=2007&d=0&e=25&f=2016&g=d&q=q&y=0&z=^GDAXI&x=.csv'
Calls: <Anonymous> ... getSymbols -> do.call -> getSymbols.yahoo -> download.file

Execution halted

当我在通常的R模式中逐行运行R代码时,我得到了预期的结果。 getSymbolsrmarkdown是否存在已知问题?

我的sessionInfo()

R version 3.1.3 (2015-03-09)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                           LC_TIME=English_United States.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] quantmod_0.4-5      TTR_0.23-0          xts_0.9-7           zoo_1.7-12          stochvol_1.2.2      coda_0.18-1        
 [7] XLConnect_0.2-11    XLConnectJars_0.2-9 plyr_1.8.3          reshape_0.8.5       svDialogs_0.9-57    svGUI_0.9-55       
[13] RODBC_1.3-12       

loaded via a namespace (and not attached):
[1] digest_0.6.8    grid_3.1.3      htmltools_0.2.6 lattice_0.20-30 Rcpp_0.12.1     rJava_0.9-7     rmarkdown_0.9.2 tools_3.1.3    
[9] yaml_2.1.13    

评论后编辑:使用setInternet2(use = TRUE)使其工作。以下工作 - 甚至在我的公司安全设置中。

---
title: "TEST"
author: "TEST"
date: "Monday, January 25, 2016"
output: html_document
---
```{r, echo=FALSE}
require(quantmod)
setInternet2(use = TRUE)
prices = invisible(getSymbols("^GDAXI", return.class = "xts", auto.assign=FALSE ))
cat(getwd())
rets = na.omit(diff(log(prices[,4]))) - mean(na.omit(diff(log(prices[,4]))))
plot(rets['2015/2016'])
```

1 个答案:

答案 0 :(得分:1)

对于您的代理问题,请使用setInternet2()

从更一般的角度来看,我更喜欢手动下载文件,将其保存在.rdata文件中(使用save())并在您的rmarkdown文件中使用load()。< / p>

它使你的编织更快(除非你使用缓存或不做错误)并且不要多次同时使用同一个文件。 (仅在一次性分析而非报告的情况下)