0

Is there a function that allows for data to be hidden in the global environment but it can still be accessed?

For example, I have a very long script with up to 100+ lines and my global environment is looking messy, there is too much and it strains my brain finding what is necessary.

I have searched up similar questions and they involve creating a package, quite frankly I have no time to learn, at this moment.

pogibas
  • 27,303
  • 19
  • 84
  • 117
Lime
  • 738
  • 5
  • 17
  • You may want to look into preventing the predicament you are in. Here is a link where the selected answer is bad practice - the second answer is better for R: https://stackoverflow.com/questions/16566799/change-variable-name-in-for-loop-using-r – Cole Nov 17 '19 at 13:53

3 Answers3

8

If you name all the objects you don't want to appear in the global environment starting with a dot (.), for example: .foo <- 'bar' the object will be accesible but will be hidden in the global environment or in any ls() call:

> .foo <- 'bar'
> .foo
[1] "bar"
> ls()
character(0)
> 

Edit: Adding a working example

MalditoBarbudo
  • 1,815
  • 12
  • 18
  • But, even if this works, and is what you asked, I would take a look at the @Roman Luštrik answer, as it will pay off on the long run if you plan using R heavily. – MalditoBarbudo Nov 17 '19 at 12:23
  • 1
    This answer also addresses the situation where RStudio displays all variables in its environment pane and you may have one you don't want displayed (for example a non-critical password used in a script). Just preface the password with `.` – Robert McDonald Sep 29 '21 at 15:42
2

Possible solutions would be:

  1. removing objects once they're not needed any more
  2. put related variables into a list (hello lapply, sapply)
  3. move into a separate custom environment (new.env())
  4. simplify the script to not use as many objects
  5. run script in batch mode and miss out on what the environment looks like altogether
Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
0

Sounds like an XY problem, 100 lines is quite small, it's likely that you are using too many temporary variables or are numbering objects that should be in a list.

You also don't mention why you don't like your environment to be "messy", my guess is that maybe you don't like the output of ls() ?

Then maybe you'll be happy to learn about the pattern argument of ls() which will allow you to filter the result, mostly useful with prefixes or suffixes as in the following examples :

something <- 1
some_var <- 2
another_var <- 3
ls(pattern ="^some")
#> [1] "some_var"  "something"
ls(pattern="var$")
#> [1] "another_var" "some_var"

Created on 2019-11-17 by the reprex package (v0.3.0)

moodymudskipper
  • 46,417
  • 11
  • 121
  • 167