How can I neatly clean my R workspace while preserving certain objects?

前端 未结 3 1561
面向向阳花
面向向阳花 2020-12-08 23:45

Suppose I\'m messing about with some data by binding vectors together, as I\'m wont to do on a lazy sunday afternoon.

    x <- rnorm(25, mean = 65, sd = 1         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-09 00:14

    I would approach this by making a separate environment in which to store all the junk variables, making your data frame using with(), then copying the ones you want to keep into the main environment. This has the advantage of being tidy, but also keeping all your objects around in case you want to look at them again.

    temp <- new.env()
    with(temp, {
        x <- rnorm(25, mean = 65, sd = 10) 
        y <- rnorm(25, mean = 75, sd = 7) 
        z <- 1:25 
        dd <- data.frame(mscore = x, vscore = y, caseid = z)
        }
    )
    
    dd <- with(temp,dd)
    

    This gives you:

    > ls()
    [1] "dd"   "temp"
    > with(temp,ls())
    [1] "dd" "x"  "y"  "z" 
    

    and of course you can get rid of the junk environment if you really want to.

提交回复
热议问题