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?
attr(e$var, 'attrib')should be'some.new.attrib'.setattrfunction fromdata.table, if you want to change attributes by reference. Tryassign_new_attrib_DT <- function(obj) data.table::setattr(obj, 'attrib', 'some.new.attrib').data.tableis a very common package, anddata.table::setattr()works on any object.