3

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?

1
  • 1
    class(eval(as.name(var))) is character, whereas argument to attribute(...) should be an object, not a character Commented Sep 14, 2017 at 8:48

1 Answer 1

1

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)))
Sign up to request clarification or add additional context in comments.

4 Comments

your solution works fine for an atomic variable but converts a dataframe object to a list. Could you please modify the answer such that the obj returned does not change to a list; just the new attribute must be added to the object,
Ah, so you don't want to replace all attributes, you want to append one?
yes, and I managed to do it by assigning a specific attribute; I used obj$attr_name<-attr_value instead of attributes(obj) <- attribute and my job is done. Thanks. Maybe you can add this part also in your answer so it becomes complete and useful in all situations.
I've modified my answer to allow modification rather than replacement of attributes

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.