Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R how to restrict the names that are in scope to those I create explicitly?

I thought that it would be enough to use fully qualified names to avoid polluting my scope with names I did not explicitly introduce, but apparently, with R, this is not the case.

For example,

% R_PROFILE_USER= /usr/bin/R --quiet --no-save --no-restore
> ls(all = TRUE)
character(0)
> load("/home/berriz/_/projects/fda/deseq/.R/data_for_deseq.RData")
> ls(all = TRUE)
[1] "a" "b" "c"
> ?rlog
No documentation for ‘rlog’ in specified packages and libraries:
you could try ‘??rlog’

So far, so good. In particular, as the last command shows, the interpreter knows nothing of rlog.

But after I run

> d <- DESeq2::DESeqDataSetFromMatrix(countData = a, colData = b, design = c)

...then, henceforth, the command ?rlog will produce a documentation page for a function I did not explicitly introduce into the environment (and did not refer to with a fully qualified name).

I find this behavior disconcerting.

In particular, I don't know when some definition I have explicitly made will be silently shadowed as a side-effect of some seemingly unrelated command.

How can I control what the environment can see?

Or to put it differently, how can I prevent side effects like the one illustrated above?

like image 899
kjo Avatar asked Jan 16 '17 21:01

kjo


1 Answers

Not sure if "scope" means the same thing in R as it may to other languages. R uses "environments" (see http://adv-r.had.co.nz/Environments.html for detailed explanation). Your scope in R includes all environments that are loaded, and as you have discovered, the user doesn't explicitly control every environment that is loaded.

For example,

ls()

lists the objects in your default environment '.GlobalEnv'

search()

lists the currently loaded environments.

ls(name='package.stats')

In default R installations, 'package:stats' is one of the environments loaded on startup.

By default, everything you create is stored in the global environment.

ls(name='.GlobalEnv')

You can explicitly reference objects you create by referencing their environment with the $ syntax.

x <- c(1,2,3)
.GlobalEnv$x
like image 142
Nathan T Alexander Avatar answered Sep 28 '22 08:09

Nathan T Alexander