Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

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

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 = 10)
    y <- rnorm(25, mean = 75, sd = 7)
    z <- 1:25

    dd <- data.frame(mscore = x, vscore = y, caseid = z)

I've now got my new dataframe dd, which is wonderful. But there's also still the detritus from my prior slicings and dicings:

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

What's a simple way to clean up my workspace if I no longer need my "source" columns, but I want to keep the dataframe? That is, now that I'm done manipulating data I'd like to just have dd and none of the smaller variables that might inadvertently mask further analysis:

    > ls()
    [1] "dd"

I feel like the solution must be of the form rm(ls[ -(dd) ]) or something, but I can't quite figure out how to say "please clean up everything BUT the following objects."

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...