I was wondering if there is anyway to get the environment of a declared variable. Say I already have declared a variable to an environment and want to use that variable's environment to declare a few more variables. Something like getEnv("variable")
相关问题
- R - Quantstart: Testing Strategy on Multiple Equit
- Using predict with svyglm
- Reshape matrix by rows
- Extract P-Values from Dunnett Test into a Table by
- split data frame into two by column value [duplica
相关文章
- How to convert summary output to a data frame?
- How to plot smoother curves in R
- Paste all possible diagonals of an n*n matrix or d
- ess-rdired: I get this error “no ESS process is as
- How to use doMC under Windows or alternative paral
- dyLimit for limited time in Dygraphs
- Saving state of Shiny app to be restored later
- How to insert pictures into each individual bar in
How about this:
Then we can:
You can get all objects in your workspace with
ls()
, so you can then check which of those are environments:I need to use
get()
there becausels()
returns character names of objects rather than the objects themselves. Now given some objectx
, we want to find which environments it exists in. All we need to do is iterate through each environment inenvirs
, and check if they contain whatever object we're looking for. Something along the lines of (checking for a variablex
):Here's a function to do all this:
This is more or less the same as what I did outside the function.
gobjects
reads fromls()
, this time explicitly checking the global environment.GlobalEnv
, since it is now within a function.envirs
is the same as before, except now it will check.GlobalEnv
as well.xin
is storing the names of which environmentsx
was found in. The line:Allows object to be tested without quotes e.g.
getEnv(x)
versusgetEnv('x')
. That's a matter of preference though, you can change it to accept characters instead.Here's a few tests.
This only checks environments created within
.GlobalEnv
. I'm sure you can work out how to extend it to search across more environments though if you need.I'm surprised there isn't some in-built function for this. Or maybe there is and I don't know about it. I've never actually needed to do anything like this before so maybe it's not actually surprising.
Refer to: http://adv-r.had.co.nz/Environments.html#env-basics
The where function is described in the above website. It only finds the first environment the variable appears in, but could easily be modified to find all.