在 R 中的表达式中使用字符串

Using a string inside an expression in R

我需要在 data.frame 上设置属性,但我想从变量传递 data.frame 名称。我尝试了几种引用、替代、解析、表达式的组合,但都没有成功。怎么做到的?

#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

如果您将 data.frame 放入列表中,这将起作用:

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

我想这是使用 data.frame 列表的额外优势。请参阅 gregor 的回答 here 以获得更多优势。

嗯,我找到了解决办法

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

这是(另一个)解决方案

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