Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning list attributes in an environment

Tags:

r

environment

The title is the self-contained question. An example clarifies it: Consider

x=list(a=1, b="name")
f <- function(){
    assign('y[["d"]]', FALSE, parent.frame() )
}
g <- function(y) {f(); print(y)}

g(x)

$a
[1] 1

$b
[1] "name"

whereas I would like to get

g(x)

$a
[1] 1

$b
[1] "name"

$d
[1] FALSE

A few remarks. I knew what is wrong in my original example, but am using it to make clear my objective. I want to avoid <<-, and want x to be changed in the parent frame.

I think my understanding of environments is primitive, and any references are appreciated.

like image 645
gappy Avatar asked Jul 16 '11 02:07

gappy


People also ask

What are the environments in R?

The environment is a virtual space that is triggered when an interpreter of a programming language is launched. Simply, the environment is a collection of all the objects, variables, and functions. Or, Environment can be assumed as a top-level object that contains the set of names/variables associated with some values.

How do you get the current environment in R?

Global environment can be referred to as . GlobalEnv in R codes as well. We can use the ls() function to show what variables and functions are defined in the current environment. Moreover, we can use the environment() function to get the current environment.

What is the parent frame in R?

The parent frame of a function evaluation is the environment in which the function was called. It is not necessarily numbered one less than the frame number of the current evaluation, nor is it the environment within which the function was defined.

How do I see objects in R?

ls. str() function kind of combines the functionality of str() function in R that helps to look at the structure of an object in R with ls() function. For example, if apply ls. str() function to the current environment, we can see the object names and its values.


1 Answers

The first argument to assign must be a variable name, not the character representation of an expression. Try replacing f with:

f <- function() with(parent.frame(), y$d <- FALSE)

Note that a, b and d are list components, not list attributes. If we wanted to add an attribute "d" to y in f's parent frame we would do this:

f <- function() with(parent.frame(), attr(y, "d") <- FALSE)

Also, note that depending on what you want to do it may (or may not) be better to have x be an environment or a proto object (from the proto package).

like image 156
G. Grothendieck Avatar answered Sep 22 '22 06:09

G. Grothendieck