Generating names iteratively in R for storing plots

后端 未结 2 575
说谎
说谎 2020-12-16 07:23

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         


        
相关标签:
2条回答
  • 2020-12-16 07:58

    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 )
    
    0 讨论(0)
  • 2020-12-16 08:12

    Have a look at the packages lattice or ggplot2, the plot functions in these packages create objects which can be assigned to variables and can be printed or plotted at a later stage.

    For instance with 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
    

    Or append the objects to a list:

    p <- list()
    p[[1]] <- xyplot(...)
    p[[2]] <- xyplot(...)
    
    0 讨论(0)
提交回复
热议问题