2009-11-29 84 views
4

我正在使用R遍歷數據框,執行計算並繪製一個繪圖。在R中爲迭代生成名稱用於存儲繪圖

for(i in 2 : 15){ 
# get data 
dataframe[,i] 

# do analysis 

# make plot 
a <- plot() 
} 

有沒有一種方法可以使用'我'的值使情節對象名稱'a'?例如,一個+「我」< - plot()。然後我想添加到一個矢量,所以我有一系列的情節,然後我可以使用在稍後階段,當我想要一個PDF。或者也許還有另一種存儲方式。

我熟悉的paste()函數,但我還沒有想出如何定義使用它的對象。

回答

6

如果你想有一個情節對象的「載體」,最簡單的方法可能是將其保存在list。使用paste()爲您的劇情創建一個名稱,然後將其添加到列表:

# Create a list to hold the plot objects. 
pltList <- list() 

for(i in 2:15){ 

    # Get data, perform analysis, ect. 

    # Create plot name. 
    pltName <- paste('a', i, sep = '') 

    # Store a plot in the list using the name as an index. 
    # Note that the plotting function used must return an *object*. 
    # Functions from the `graphics` package, such as `plot`, do not return objects. 
    pltList[[ pltName ]] <- some_plotting_function() 

} 

如果你不想地塊存儲在列表和字面想創建一個新的對象,它有名字包含在pltName,那麼你可以使用assign()

# Use assign to create a new object in the Global Environment 
# that gets it's name from the value of pltName and it's contents 
# from the results of plot() 
assign(pltName, plot(), envir = .GlobalEnv) 
+0

謝謝你們的答案 - 他們是非常有幫助的。 – womble 2009-11-29 20:03:11

4

查看軟件包latticeggplot2,這些軟件包中的繪圖功能可創建可分配給變量的對象,並可在稍後階段打印或繪圖。

例如與lattice

library("lattice") 
i <- 1 
assign(sprintf("a%d", i), xyplot(1:10 ~ 1:10)) 
print(a1) # you have to "print" or "plot" the objects explicitly 

或者對象追加到一個列表:

p <- list() 
p[[1]] <- xyplot(...) 
p[[2]] <- xyplot(...)