Lazarus Thurston
Lazarus Thurston

Reputation: 1287

How to set a specific attribute of an object if the object name is in a variable?

Normally you would set the attribute of an object as

attributes(x) <- list(dummy = 123)

But I have the variable names stored in a character vector. The following code throws an error:

var <- "x"
attributes(eval(as.name(var))) <- list(dummy = 123)

Error in attributes(eval(as.name(var))) <- list(dummy = 123) : could not find function "eval<-"

If eval(as.name()) is not the right way could someone suggest a way to solve this problem?

Upvotes: 3

Views: 419

Answers (1)

sebastian-c
sebastian-c

Reputation: 15405

You can use a function to apply the attributes and the assign function to apply them:

add_dummy <- function(obj, name, attribute){
  attr(obj, name) <- attribute
  return(obj)
}

assign(var, add_dummy(get(var), "attr_name", list(dummy = 123)))

Upvotes: 1

Related Questions