R中的定义变量列表

时间:2012-03-16 19:49:28

标签: r

我在Linux中使用R,仅限命令行。

一段时间后回到项目中,我忘记了我使用的变量名,而R命令历史记录并没有包含它们。

我似乎记得有一个列出所有用户定义变量的命令,但不记得它是什么,并且无法在网上找到它。

如何在R?

中列出所有用户定义的变量

2 个答案:

答案 0 :(得分:45)

ls()

从帮助页面:

 ‘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’.

编辑:我应该注意列出你需要使用的所有变量

ls(all.names = TRUE)

否则以点开头的变量将不会显示在列表中。

答案 1 :(得分:2)

您可以查看此链接:

Tricks to manage the available memory in an R session

它具有很好的功能,可以显示对象及其内存使用情况。这是我的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)
}