0

I need to set an attribute on a data.frame, but I want to pass the data.frame name from a variable. I have tried several combinations of quote, substitute, parse, expression with no success. How it can be done?

#OK code

my_data_frame <- data_frame(col = 1:10)
attr(my_data_frame, "attr1") <- 1L
attributes(my_data_frame)

#Not OK code  

df_name <- "my_data_frame"

attr(as.name(df_name), "attr2") <- 2L #this does not work
attr(quote(eval(df_name)), "attr2") <- 2L #this does not work
attr(parse(text = eval(df_name)), "attr2") <- 2L #this also don't work
Fernando Macedo
  • 355
  • 3
  • 7

3 Answers3

2

Well, I have found a solution

eval(substitute(attr(a, "attr2") <- 225L, list(a = as.name(df_name))))
Fernando Macedo
  • 355
  • 3
  • 7
1

This will work if you put your data.frame into a list:

myList <- list(my_data_frame=my_data_frame)

# add attribute
attr(myList[[df_name]], "attr2") <- 2L

# check
attr(myList[[df_name]], "attr2")
[1] 2

# return to data.frame
my_data_frame <- myList[[df_name]]

# check regular data.frame
attr(my_data_frame, "attr2")
[1] 2

I guess this is an additional advantage to working with lists of data.frames. See gregor's answer here for additional advantages.

Community
  • 1
  • 1
lmo
  • 37,904
  • 9
  • 56
  • 69
1

Here is (another) solution

my_data_frame <- data_frame(col = 1:10)
attr(my_data_frame, "attr1") <- 1L
attributes(my_data_frame)

df_name <- "my_data_frame"

assign_attr <- function(obj_name, attr_name, value) {
    temp_obj <- get(obj_name, envir=parent.frame(2))
    attr(temp_obj, attr_name) <- value
    assign(obj_name, temp_obj, envir=parent.frame(2))
}

assign_attr(df_name, "attr1", 1)
print(attributes(my_data_frame))
thc
  • 9,527
  • 1
  • 24
  • 39
  • Note that you can't do: attr(get(df_name), "attr1") <- 1. It would be the most logical solution, but is not implemented in R for some reason. – thc Jan 18 '17 at 20:13