我正在使用 R 遍历数据框,执行计算并绘制绘图。
for(i in 2 : 15){
# get data
dataframe[,i]
# do analysis
# make plot
a <- plot()
}
有没有办法使用“i”的值使绘图对象名称为“a”?例如,a + "i"<- plot()。然后我想将它添加到一个向量中,这样我就有了一系列的图,然后我可以在以后制作 pdf 时使用这些图。或者也许有另一种存储方式。
我熟悉 paste() 函数,但我还没有弄清楚如何使用它来定义一个对象。
最佳答案
如果您想要绘图对象的“向量”,最简单的方法可能是将它们存储在 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 )
关于r - 在 R 中迭代生成名称以存储绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1816480/