Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
555 views
in Technique[技术] by (71.8m points)

object - Generating names iteratively in R for storing plots

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()
}

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

}

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 )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...