Tricks to manage the available memory in an R session

前端 未结 27 1499
情深已故
情深已故 2020-11-22 01:23

What tricks do people use to manage the available memory of an interactive R session? I use the functions below [based on postings by Petr Pikal and David Hinds to the r-he

27条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 01:54

    Tip for dealing with objects requiring heavy intermediate calculation: When using objects that require a lot of heavy calculation and intermediate steps to create, I often find it useful to write a chunk of code with the function to create the object, and then a separate chunk of code that gives me the option either to generate and save the object as an rmd file, or load it externally from an rmd file I have already previously saved. This is especially easy to do in R Markdown using the following code-chunk structure.

    ```{r Create OBJECT}
    
    COMPLICATED.FUNCTION <- function(...) { Do heavy calculations needing lots of memory;
                                            Output OBJECT; }
    
    ```
    ```{r Generate or load OBJECT}
    
    LOAD <- TRUE;
    #NOTE: Set LOAD to TRUE if you want to load saved file
    #NOTE: Set LOAD to FALSE if you want to generate and save
    
    if(LOAD == TRUE) { OBJECT <- readRDS(file = 'MySavedObject.rds'); } else
                     { OBJECT <- COMPLICATED.FUNCTION(x, y, z);
                                 saveRDS(file = 'MySavedObject.rds', object = OBJECT); }
    
    ```
    

    With this code structure, all I need to do is to change LOAD depending on whether I want to generate and save the object, or load it directly from an existing saved file. (Of course, I have to generate it and save it the first time, but after this I have the option of loading it.) Setting LOAD = TRUE bypasses use of my complicated function and avoids all of the heavy computation therein. This method still requires enough memory to store the object of interest, but it saves you from having to calculate it each time you run your code. For objects that require a lot of heavy calculation of intermediate steps (e.g., for calculations involving loops over large arrays) this can save a substantial amount of time and computation.

提交回复
热议问题