Tricks to manage the available memory in an R session

前端 未结 27 1503
情深已故
情深已故 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:56

    I quite like the improved objects function developed by Dirk. Much of the time though, a more basic output with the object name and size is sufficient for me. Here's a simpler function with a similar objective. Memory use can be ordered alphabetically or by size, can be limited to a certain number of objects, and can be ordered ascending or descending. Also, I often work with data that are 1GB+, so the function changes units accordingly.

    showMemoryUse <- function(sort="size", decreasing=FALSE, limit) {
    
      objectList <- ls(parent.frame())
    
      oneKB <- 1024
      oneMB <- 1048576
      oneGB <- 1073741824
    
      memoryUse <- sapply(objectList, function(x) as.numeric(object.size(eval(parse(text=x)))))
    
      memListing <- sapply(memoryUse, function(size) {
            if (size >= oneGB) return(paste(round(size/oneGB,2), "GB"))
            else if (size >= oneMB) return(paste(round(size/oneMB,2), "MB"))
            else if (size >= oneKB) return(paste(round(size/oneKB,2), "kB"))
            else return(paste(size, "bytes"))
          })
    
      memListing <- data.frame(objectName=names(memListing),memorySize=memListing,row.names=NULL)
    
      if (sort=="alphabetical") memListing <- memListing[order(memListing$objectName,decreasing=decreasing),] 
      else memListing <- memListing[order(memoryUse,decreasing=decreasing),] #will run if sort not specified or "size"
    
      if(!missing(limit)) memListing <- memListing[1:limit,]
    
      print(memListing, row.names=FALSE)
      return(invisible(memListing))
    }
    

    And here is some example output:

    > showMemoryUse(decreasing=TRUE, limit=5)
          objectName memorySize
           coherData  713.75 MB
     spec.pgram_mine  149.63 kB
           stoch.reg  145.88 kB
          describeBy    82.5 kB
          lmBandpass   68.41 kB
    

提交回复
热议问题