John Doucette
John Doucette

Reputation: 4520

List of Defined Variables in R

I'm using R in linux, command line only.

Coming back to a project after some time, I have forgotten the variable names I used, and the R command history doesn't contain them.

I seem to remember there being a command which lists all user defined variables, but don't remember what it is, and cannot find it on the web.

How can I list all the user defined variables in R?

Upvotes: 33

Views: 76310

Answers (2)

screechOwl
screechOwl

Reputation: 28159

You may want to check out this link:

Tricks to manage the available memory in an R session

It has a great function to show objects along with their memory usage. It's part of my start-up script for R.

# Written by Dirk Eddelbuettel found here: https://stackoverflow.com/questions/1358003/tricks-to-manage-the-available-memory-in-an-r-session

# 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.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.dim)
    names(out) <- c("Type", "Size", "Rows", "Columns")
    if (!missing(order.by))
        out <- out[order(out[[order.by]], decreasing=decreasing), ]
    if (head)
        out <- head(out, n)
    out
}
# shorthand
lsos <- function(..., n=10) {
    .ls.objects(..., order.by="Size", decreasing=TRUE, head=TRUE, n=n)
}

Upvotes: 3

Dason
Dason

Reputation: 61933

ls()

From the help page:

 ‘ls’ and ‘objects’ return a vector of character strings giving the
 names of the objects in the specified environment.  When invoked
 with no argument at the top level prompt, ‘ls’ shows what data
 sets and functions a user has defined.  When invoked with no
 argument inside a function, ‘ls’ returns the names of the
 functions local variables.  This is useful in conjunction with
 ‘browser’.

Edit: I should note that to list ALL variables you would need to use

ls(all.names = TRUE)

otherwise variables that begin with a dot won't show up in the listing.

Upvotes: 52

Related Questions