Fernando Macedo
Fernando Macedo

Reputation: 365

Using a string inside an expression in R

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

Upvotes: 0

Views: 91

Answers (3)

thc
thc

Reputation: 9705

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))

Upvotes: 1

Fernando Macedo
Fernando Macedo

Reputation: 365

Well, I have found a solution

eval(substitute(attr(a, "attr2") <- 225L, list(a = as.name(df_name))))

Upvotes: 2

lmo
lmo

Reputation: 38500

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.

Upvotes: 1

Related Questions