2016-03-02 13 views
0

我想通過一個腳本運行並製作很多地塊,但只在最後的地塊然後出來降價
所以我試圖做的是保存許多地塊作爲一張地塊列表,但不會將它們發佈到降價。
第二步是去列表和繪製三分之一的情節,但由於某種原因,我只得到最後一塊情節。
在knitr上繪製三分之一的地塊

#+ setup, include=FALSE 

library(knitr) 
opts_chunk$set(fig.path = 'figure/silk-', fig.width = 10, fig.height = 10) 

#' Make a list of plots. 
#' 
#/* do not show in Markdown 
index = 1 
plots<-list() 
for (let in letters) 
{ 
plot(c(index:100)) 
assign(let,recordPlot()) 
plot.new() 
plots[index]<-(let) 
index=index+1 
} 
#*/go through list of plots and plot then to markdown file 
for (p in seq(from = 1, to = length(plots), by =3)) 
{ 

    print(get(plots[[p]])) 

} 

回答

2

有代碼中的一些錯誤來自其他編程語言的遺物:

  • 不要使用assign可言。允許使用分配的人不會使用它。
  • plot.new()創建一個空白頁面。退出
  • 請勿使用get。它在S-Plus中有其用途,但現在沒有幫助。
  • 帶有列表,使用[[,例如, plots[[index]]
  • 最重要的是:你想要什麼是合理的,但標準圖形(例如情節)非常適合這個,因爲它是在考慮行動的基礎上構建的,而不是賦值。 latticeggplot2圖形都是分配感知的。
  • 在此示例中,我使用lapply作爲標準R實踐的演示。在這種情況下for循環不會更慢,因爲繪圖佔用大部分時間。
  • 爲此更好地使用刻面或面板,而不是許多獨立的地塊。

`

library(knitr) 
library(lattice) 
# Make a list of plots. 
# do not show in Markdown 
plots = lapply(letters[1:3], 
    function(letter) {xyplot(rnorm(100)~rnorm(100), main=letter)}) 

# print can use a list (not useful in this case)  
print(plots) 

# go through list of plots and plot then to markdown file 
# This only makes sense if you do some paging in between. 
for (p in seq(from = 1, to = length(plots), by =3)) 
{ 
    print(plots[[p]]) 
} 
+0

謝謝! 1.我不確定我是否理解了你的一些評論:「允許使用分配的人不會使用它」(?) 2.你把循環應用到這是一個很好的練習,但是當我註釋掉應用功能,只使用最後一個for循環,我仍然只得到最後一個記錄 – eliavs

+1

這是2001年左右r-help的一個引用,當時我使用了類似工作中的assign。請參閱http://markmail.org/message/w3hwkqs6e57wbuie和許多其他地方。 –

+0

當你評論lapply函數時,你什麼也沒有,或者更好的是你最後一次運行的遺蹟。在重新運行之前重新啓動R –

相關問題