2

Here is a simplified example:

e <- new.env()
e$var <- 'some.val'
attr(e$var, 'attrib') <- 'some.attrib' 
attr(e$var, 'attrib')
#[1] "some.attrib"

assign_new_attrib <- function(obj) {
   attr(obj, 'attrib') <<- 'some.new.attrib'
}

assign_new_attrib(e$var)
#Error in attr(obj, "attrib") <<- "some.new.attrib" : 
#  object 'obj' not found
attr(e$var, 'attrib')
#[1] "some.attrib"

I have a variable var in environment e which has an attribute attrib. Now I have a function assign_new_attrib which takes a object and assigns it a new attribute attrib. As you can see, the above code results in a error "object 'obj' not found" due to the fact that <<- can not resolve the variable from within the function.

How can I define function assign_new_attrib() to assign the new attribute by referece?

4
  • Use <- rather than <<- Commented Nov 24, 2017 at 17:07
  • If its not clear: the final result of attr(e$var, 'attrib') should be 'some.new.attrib'. Commented Nov 24, 2017 at 17:09
  • 3
    See the setattr function from data.table, if you want to change attributes by reference. Try assign_new_attrib_DT <- function(obj) data.table::setattr(obj, 'attrib', 'some.new.attrib'). Commented Nov 24, 2017 at 17:18
  • @nicola, that is a good answer. Don't know why you put it as a comment. I would definitely accept it! data.table is a very common package, and data.table::setattr() works on any object. Commented Nov 24, 2017 at 17:24

1 Answer 1

1

From the comments by nicola:

See the setattr function from data.table, if you want to change attributes by reference. Try:

assign_new_attrib_DT <- function(obj) data.table::setattr(obj, 'attrib', 'some.new.attrib')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.