Manage the available memory in an R session

r-project

A small function to manage memory in R.

Author

Affiliation

Vitor Chagas

 

Published

July 11, 2010

Citation

Chagas, 2010

Memory is something that we always need to keep track of in R.

Here’s a nice trick found in stackoverflow.com

# improved list of objects
.ls.objects <- function(pos = 1, pattern, order.by, decreasing = FALSE, head = FALSE, 
    n = 5) {
    napply <- function(names, fn) sapply(names, function(x) fn(get(x, pos = pos)))
    names <- ls(pos = pos, pattern = pattern)
    obj.class <- napply(names, function(x) as.character(class(x))[1])
    obj.mode <- napply(names, mode)
    obj.type <- ifelse(is.na(obj.class), obj.mode, obj.class)
    obj.size <- napply(names, object.size)
    obj.prettysize <- sapply(obj.size, function(r) prettyNum(r, big.mark = ","))
    obj.dim <- t(napply(names, function(x) as.numeric(dim(x))[1:2]))
    vec <- is.na(obj.dim)[, 1] & (obj.type != "function")
    obj.dim[vec, 1] <- napply(names, length)[vec]
    out <- data.frame(obj.type, obj.size, obj.prettysize, obj.dim)
    names(out) <- c("Type", "Size", "PrettySize", "Rows", "Columns")
    if (!missing(order.by)) 
        out <- out[order(out[[order.by]], decreasing = decreasing), ]
    out <- out[c("Type", "PrettySize", "Rows", "Columns")]
    names(out) <- c("Type", "Size", "Rows", "Columns")
    if (head) 
        out <- head(out, n)
    out
}

# shorthand
lsos <- function(..., n = 10) {
    .ls.objects(..., order.by = "Size", decreasing = TRUE, head = TRUE, n = n)
}

This one is going to my .Rprofile.

Footnotes

    Citation

    For attribution, please cite this work as

    Chagas (2010, July 11). A Portuguese Actuary: Manage the available memory in an R session. Retrieved from http://vchagas69.github.io/posts/2010-07-11-manage-the-available-memory-in-an-r-session/

    BibTeX citation

    @misc{chagas2010manage,
      author = {Chagas, Vitor},
      title = {A Portuguese Actuary: Manage the available memory in an R session},
      url = {http://vchagas69.github.io/posts/2010-07-11-manage-the-available-memory-in-an-r-session/},
      year = {2010}
    }