Skip to content

Instantly share code, notes, and snippets.

@nstjhp
Created January 8, 2021 13:50
Show Gist options
  • Save nstjhp/db4e65962f781ed5700d9eb480c865dc to your computer and use it in GitHub Desktop.
Save nstjhp/db4e65962f781ed5700d9eb480c865dc to your computer and use it in GitHub Desktop.
Get all R object sizes
# From comments on https://stackoverflow.com/a/19610840/3275826
# and https://stackoverflow.com/a/1395280/3275826
#
# Using mget can avoid the problems of having an object with the same name
# as the function argument confusing the results, here `x` in the line
# `sizes = sapply(list_obj, function(x) object.size(get(x)), simplify = FALSE)`
# If you were to use this instead and assigned x to a large enough object,
# then the output of this function would be different to a straight object.size(x) call
#
# object.size can be replaced by pryr::object_size
#
# To use, just call ls_obj_sizes()
#
ls_obj_sizes = function(list_obj = ls(envir = .GlobalEnv)) {
sizes = sapply(mget(list_obj, inherits=TRUE), object.size, simplify = FALSE)
print(sapply(sizes[order(-as.integer(sizes))], function(s) format(s, unit = "auto")))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment