在R中,如何获取对象';发送到函数后的名称?

在R中,如何获取对象';发送到函数后的名称?,r,R,我正在寻找get()的反面 给定一个对象名,我希望直接从对象中提取表示该对象的字符串 一个简单的例子,foo是我正在寻找的函数的占位符 z <- data.frame(x=1:10, y=1:10) test <- function(a){ mean.x <- mean(a$x) print(foo(a)) return(mean.x)} test(z) 在我目前的问题中,我的工作重点是: test <- function(a="z"){ mean.

我正在寻找
get()
的反面

给定一个对象名,我希望直接从对象中提取表示该对象的字符串

一个简单的例子,
foo
是我正在寻找的函数的占位符

z <- data.frame(x=1:10, y=1:10)

test <- function(a){
  mean.x <- mean(a$x)
  print(foo(a))
  return(mean.x)}

test(z)
在我目前的问题中,我的工作重点是:

test <- function(a="z"){
  mean.x <- mean(get(a)$x)
  print(a)
  return(mean.x)}

test("z")

test旧的deparse替代技巧:

a<-data.frame(x=1:10,y=1:10)
test<-function(z){
   mean.x<-mean(z$x)
   nm <-deparse(substitute(z))
   print(nm)
   return(mean.x)}

 test(a)
#[1] "a"   ... this is the side-effect of the print() call
#          ... you could have done something useful with that character value
#[1] 5.5   ... this is the result of the function call

请注意,对于打印方法,其行为可能会有所不同

print.foo=function(x){ print(deparse(substitute(x))) }
test = list(a=1, b=2)
class(test)="foo"
#this shows "test" as expected
print(test)

#this (just typing 'test' on the R command line)
test
#shows
#"structure(list(a = 1, b = 2), .Names = c(\"a\", \"b\"), class = \"foo\")"
我在论坛上看到的其他评论表明,最后的行为是不可避免的。如果您正在为包编写打印方法,这是很不幸的

deparse(quote(var))
我的直觉 其中引号冻结了求值中的变量或表达式
deparse函数是parse函数的逆函数,它使冻结的符号返回字符串

我认为
deparse(replacement(…)
是一个糟糕的例子,尽管变量名为“z”,要测试的参数也名为“z”。。。打印“z”并不能真正告诉您当时是否正确;-)@Tommy,试图改进它,但是如果你愿意的话,请通过编辑来改进。R中的
get
的反面是
assign
,但我不确定这是你真正想要的…也许它应该是:
print.foo=function(x){cat(deparse(substitute(x))}
print.foo=function(x){print(deparse(substitute(x)),quote=FALSE)}
print.foo=function(x){print.default(as.list(x))}
as.list()
不起作用,因为“test”可以是任何东西。我刚刚在我的玩具示例中使用了一个列表。R3.6更新。现在行为有了一点变化,但仍然没有固定下来<代码>打印(测试)
生成
test
,而命令行上的
test
生成
x
(而不是
test
)。所有这些都有相同的行为
print.foo=function(x){print(deparse(substitute(x))}
print.foo=function(x){cat(deparse(substitute(x))}
print.foo=function(x){print(deparse(substitute(x)),quote=FALSE)}
print.foo=function(x){ print(deparse(substitute(x))) }
test = list(a=1, b=2)
class(test)="foo"
#this shows "test" as expected
print(test)

#this (just typing 'test' on the R command line)
test
#shows
#"structure(list(a = 1, b = 2), .Names = c(\"a\", \"b\"), class = \"foo\")"
deparse(quote(var))