2016-02-04 41 views
5

我嘗試使用循環或樂句在Rmarkdown文檔中創建多個圖形數字。在rmarkdown(knitr chunk)文檔中生成的多重(R)圖形數字

將R腳本:

require(plotly) 
data(iris) 
b <- lapply(setdiff(names(iris), c("Sepal.Length","Species")), 
      function(x) { 
       plot_ly(iris, 
         x = iris[["Sepal.Length"]], 
         y = iris[[x]], 
         mode = "markers") 
      }) 
print(b) 

作品很好,但它包含在knitr塊時失敗:

--- 
output: html_document 
--- 

```{r,results='asis'} 
require(plotly) 
data(iris) 
b <- lapply(setdiff(names(iris), c("Sepal.Length","Species")), 
      function(x) { 
       plot_ly(iris, 
         x = iris[["Sepal.Length"]], 
         y = iris[[x]], 
         mode = "markers") 
      }) 
print(b) 
``` 

我試着用的lapplyevalparse但只有一個組合替換print(b)顯示最後的數字。

我懷疑是一個範圍問題/環境問題,但我沒有找到任何解決方案。

謝謝你的幫助。

回答

4

而不是print(b),把b放在htmltools::tagList(),例如,

```{r} 
library(plotly) 
b <- lapply(
    setdiff(names(iris), c("Sepal.Length","Species")), 
    function(x) { 
    as.widget(plot_ly(iris, 
      x = iris[["Sepal.Length"]], 
      y = iris[[x]], 
      mode = "markers")) 
    } 
) 
htmltools::tagList(b) 
``` 

注意這個目前需要的plotly on Github開發版本(> = 2.0.29)。

+0

感謝您的幫助。但它不起作用。我看到警告消息: – frdbd

+0

## charToRaw(text)中的警告:參數應該是長度爲1的字符串(大約transl。) – frdbd

+0

它看起來像函數tagList()將圖的數據作爲輸入,而不是生成的數字在js)。 – frdbd

3

我發現通過使用臨時文件和kniting這是一個「髒」的解決方案:

```{r,echo=FALSE} 
mytempfile<-tempfile() 
write("```{r graphlist,echo=FALSE}\n",file=mytempfile) 
write(paste("p[[",1:length(p),"]]"),file=mytempfile,append = TRUE) 
write("\n```",file=mytempfile,append = TRUE) 
``` 

`r knit_child(mytempfile, quiet=T)` 

但它是不能令人滿意的。

+0

工程就像一個魅力! –

相關問題