Assigning List Attributes in an Environment

The name is a self-sufficient question. An example clarifies this: 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 comments. I knew what was wrong in my original example, but I use it to clarify my purpose. I want to avoid <<- and I want x to be changed in the parent frame.

I think my understanding of the environment is primitive and any references are appreciated.

+6
source share
2 answers

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

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

Note that a , b and d are components of a list, not list attributes. If we wanted to add the attribute "d" to y in f 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 not) be better to have x environment or proto-object (from proto-package).

+6
source

assign The first argument must be the name of the object. Your use of assign basically matches the counter example at the end of the assignment help page. Note:

 > x=list(a=1, b="name") > f <- function(){ + assign('x["d"]', FALSE, parent.frame() ) + } > g <- function(y) {f(); print(`x["d"]`)} > g(x) [1] FALSE # a variable with the name `x["d"]` was created 

This may be the place where you want to use "<<-", but it is usually considered suspicious.

 > f <- function(){ + x$d <<- FALSE + } > g <- function(y) {f(); print(y)} > g(x) $a [1] 1 $b [1] "name" $d [1] FALSE 

Further thought, proposed in the absence of any purpose for this exercise and ignoring the term โ€œattributesโ€ that Gabor has indicated, has a definite meaning in R, but it may not have been your goal. If all you need is a result that meets your specifications, then this will achieve this goal, but note that no x changes in the global environment occur.

 > f <- function(){ + assign('y', c(x, d=FALSE), parent.frame() ) + } > g <- function(y) {f(); print(y)} > g(x) $a [1] 1 $b [1] "name" $d [1] FALSE > x # `x` is unchanged $a [1] 1 $b [1] "name" 

The parent frame for f is what can be called the "internal element of g , but the change does not apply to the global environment.

+3
source

Source: https://habr.com/ru/post/892873/


All Articles