Environments

R environments can be described to the Python user as an hybrid of a dictionary and a scope.

The first of all environments is called the Global Environment, that can also be referred to as the R workspace.

An R environment in RPy2 can be seen as a kind of Python dictionnary.

Assigning a value to a symbol in an environment has been made as simple as assigning a value to a key in a Python dictionary:

>>> robjects.r.ls(globalenv)
>>> robjects.globalenv["a"] = 123
>>> print(robjects.r.ls(globalenv))

Care must be taken when assigning objects into an environment such as the Global Environment, as this can hide other objects with an identical name. The following example should make one measure that this can mean trouble if no care is taken:

>>> globalenv["pi"] = 123
>>> print(robjects.r.pi)
[1] 123
>>>
>>> robjects.r.rm("pi")
>>> print(robjects.r.pi)
[1] 3.1415926535897931

The class inherits from the class rpy2.rinterface.SexpEnvironment.

An environment is also iter-able, returning all the symbols (keys) it contains:

>>> env = robjects.r.baseenv()
>>> [x for x in env]
<a long list returned>

Note

Although there is a natural link between environment and R packages, one should consider using the convenience wrapper dedicated to model R packages (see R packages).

class rpy2.robjects.Environment(o=None)[source]

Bases: rpy2.robjects.robject.RObjectMixin, rpy2.rinterface.SexpEnvironment

An R environement, implementing Python’s mapping interface.

clear() → None. Remove all items from D.[source]
find(item, wantfun=False)[source]

Find an item, starting with this R environment.

Raises a KeyError if the key cannot be found.

This method is called find because it is somewhat different from the method get() in Python mappings such dict. This is looking for a key across enclosing environments, returning the first key found.

Parameters

item – string (name/symbol)

Return type

object (as returned by conversion.converter.rpy2py())

items() → Generator[source]

Iterate through the symbols and associated objects in this R environment.

keys() → Generator[[str, None], None][source]

Return an iterator over keys in the environment.

pop(k[, d]) → v, remove the specified key[source]

and return the corresponding value. If the key is not found, d is returned if given, otherwise KeyError is raised.

popitem() -> (k, v), remove and return some (key, value)[source]

pair as a 2-tuple; but raise KeyError if E is empty.

values() → Generator[source]

Iterate through the objects in this R environment.