Skip to content

Instantly share code, notes, and snippets.

@jeffwong
Last active December 17, 2015 10:19
Show Gist options
  • Save jeffwong/5593586 to your computer and use it in GitHub Desktop.
Save jeffwong/5593586 to your computer and use it in GitHub Desktop.
Get memory usage for R objects loaded in the current workspace
.ls.objects <- function (pos = 1, pattern, 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")
out <- out[order(out[["Size"]], decreasing=T), ]
out <- out[c("Type", "PrettySize", "Rows", "Columns")]
names(out) <- c("Type", "Size", "Rows", "Columns")
if (head)
out <- head(out, n)
out
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment