remove all variables except functions

后端 未结 5 1426
耶瑟儿~
耶瑟儿~ 2020-12-12 09:43

I have loaded in a R console different type of objects. I can remove them all using

rm(list=ls())

or remove only the functions (but not the

5条回答
  •  无人及你
    2020-12-12 10:46

    Here's a pretty convenient function I picked up somewhere and adjusted a little. Might be nice to keep in the directory.

    list.objects <- function(env = .GlobalEnv) 
    {
        if(!is.environment(env)){
            env <- deparse(substitute(env))
            stop(sprintf('"%s" must be an environment', env))
        }
        obj.type <- function(x) class(get(x, envir = env))
        foo <- sapply(ls(envir = env), obj.type)
        object.name <- names(foo)
        names(foo) <- seq(length(foo))
        dd <- data.frame(CLASS = foo, OBJECT = object.name, 
                         stringsAsFactors = FALSE)
        dd[order(dd$CLASS),]
    }
    
    > x <- 1:5
    > d <- data.frame(x)
    > list.objects()
    #        CLASS       OBJECT
    # 1 data.frame            d
    # 2   function list.objects
    # 3    integer            x 
    > list.objects(env = x)
    # Error in list.objects(env = x) : "x" must be an environment
    

提交回复
热议问题