如何在保留某些对象的同时整洁地清理我的 R 工作区? [英] How can I neatly clean my R workspace while preserving certain objects?

查看:19
本文介绍了如何在保留某些对象的同时整洁地清理我的 R 工作区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我通过将向量绑定在一起来处理一些数据,因为我不会在一个慵懒的周日下午这样做.

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)

我现在有了我的新数据框 dd,这很棒.但是我之前的切片和切块仍然有碎屑:

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"         

如果我不再需要源"列,但我想保留数据框,有什么简单的方法可以清理我的工作区?也就是说,现在我已经完成了对数据的操作,我只想拥有 dd 而没有任何可能无意中掩盖进一步分析的较小变量:

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"

我觉得解决方案必须采用 rm(ls[ -(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."

推荐答案

我会通过创建一个单独的环境来存储所有垃圾变量来解决这个问题,使用 with() 制作您的数据框,然后将要保留的内容复制到主环境中.这样做的好处是整洁,而且还可以将所有物品放在周围,以防您想再次查看它们.

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)

这给你:

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

这篇关于如何在保留某些对象的同时整洁地清理我的 R 工作区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆