R:如何将变量名转换为字符串

我想将object1变成一个名为“ object1”的字符串

object1 = c(1 ,2 ,3)
object2 = c(3 ,2 ,1)

my_list = list(object1,object2)

for(var in my_list){
  cat(toString(var),"\n")
}

这回来

1, 2, 3 
3, 2, 1

我要它回来

"object1"
"object2"
评论
  • desse
    desse 回复

    如果您想模仿默认的绘图行为:

    my_x_var = 1:10
    my_y_var = 10:1
    
    plot(my_x_var, my_y_var)
    

    sample plot

    The way that's done is with deparse1(substitute(.)):

    deparse1(substitute(my_x_var))
    # [1] "my_x_var"
    
  • ab_non
    ab_non 回复

    There is no information of "object1" and "object2" in my_list.

    您需要这样命名它们:

    my_list = list(object1 = object1,object2 = object2)
    

    Or using tibble's lst

    my_list <- tibble::lst(object1, object2)
    

    这样您就可以使用

    names(my_list)
    #[1] "object1" "object2"