在R中迭代生成名称以存储图 [英] Generating names iteratively in R for storing plots

查看:67
本文介绍了在R中迭代生成名称以存储图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用R遍历数据帧,执行计算并绘制图.

I'm using R to loop through a data frame, perform a calculation and to make a plot.

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

# do analysis

# make plot
a <- plot()
}

有没有一种方法可以使用"i"的值来创建绘图对象名称"a"?例如,+"i"<-plot().然后,我想将其添加到矢量中,以便获得一系列绘图,以便以后在要生成pdf时可以使用.也许还有另一种存储方式.

Is there a way that I can make the plot object name 'a', using the value of 'i'? For example, a + "i" <- plot(). Then I want to add that to a vector so I have a series of plots that I can then use at a later stage when I want to make a pdf. Or perhaps there is another way of storing this.

我熟悉paste()函数,但是我还没有弄清楚如何使用它来定义对象.

I'm familiar with the paste() function but I haven't figured out how to define an object using it.

推荐答案

如果您想要绘图对象的向量",最简单的方法可能是将它们存储在list中.使用paste()为您的绘图创建一个名称,然后将其添加到列表中:

If you want a "vector" of plot objects, the easiest way is probably to store them in a list. Use paste() to create a name for your plot and then add it to the list:

# 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():

If you didn't want to store the plots in a list and literally wanted to create a new object that had the name contained in pltName, then you could use 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中迭代生成名称以存储图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆