如何将变量(对象)名称转换为String

nev*_*int 95 string r object

我有以下数据框和变量名称"foo";

 > foo <-c(3,4);
Run Code Online (Sandbox Code Playgroud)

我想要做的是转换"foo"成一个字符串.所以在函数中我不必重新创建另一个额外的变量:

   output <- myfunc(foo)
   myfunc <- function(v1) {
     # do something with v1
     # so that it prints "FOO" when 
     # this function is called 
     #
     # instead of the values (3,4)
     return ()
   }
Run Code Online (Sandbox Code Playgroud)

Sve*_*ein 205

您可以使用deparsesubstitute获取函数参数的名称:

myfunc <- function(v1) {
  deparse(substitute(v1))
}

myfunc(foo)
[1] "foo"
Run Code Online (Sandbox Code Playgroud)

  • 你会如何使用多个对象?具体来说,您将如何以一种方式为每个对象名称获取单独的字符串?(例如,如果我有对象foo,foo1和foo2,我想创建一个名称列表作为单独的字符串). (4认同)
  • @SvenHohenstein当你使用for循环时这不起作用... (4认同)
  • @MahdiJadaliha你可以尝试这个函数:`myfunc < - function(v1){s < - substitute(v1); if(length(s)== 1)deparse(s)else sub("\\(.","",s [2])}`. (2认同)
  • @theforestecologist如果函数有多个参数,你可以对每个参数使用`deparse(substitute(.))`,将结果存储在一个变量中,然后将变量放在一个列表中. (2认同)
  • 您还可以使用 deparse(quote(var)) ,其中引用冻结评估中的 var 和 deparse 是 parse 的逆,使符号回到字符串 (2认同)