在R中,如何在将对象发送给函数后获取其名称?


135

我正在寻找的反面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)

将打印:

  "z"

我的解决方法是在当前问题中更难实现:

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

test("z")

35
我想deparse(substitute(...))您正在追求的是
追逐

2
一个不好的例子,虽然变量名为“ z”,而要测试的参数称为“ z” ...打印“ z”并不能真正告诉您那时是否正确;-)
Tommy,

@Tommy,尝试对其进行改进,但如果需要,请通过编辑进行改进。
EtienneLow-Décarie'12年

getR 的反义词是,assign但我不确定这就是您真正要寻找的东西
汤姆·凯利

Answers:


160

旧的替代方法:

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

编辑:用新的测试对象运行它

注意:当将一组列表项从第一个参数传递到时,这在本地函数内将不会成功lapply(当从给定于for-loop 的列表中传递对象时,也会失败)。如果是正在处理的命名向量,则“ .Names”-属性和结构结果的处理顺序。

> lapply( list(a=4,b=5), function(x) {nm <- deparse(substitute(x)); strsplit(nm, '\\[')} )
$a
$a[[1]]
[1] "X"    ""     "1L]]"


$b
$b[[1]]
[1] "X"    ""     "2L]]"

> lapply( c(a=4,b=5), function(x) {nm <- deparse(substitute(x)); strsplit(nm, '\\[')} )
$a
$a[[1]]
[1] "structure(c(4, 5), .Names = c(\"a\", \"b\"))" ""                                            
[3] "1L]]"                                        


$b
$b[[1]]
[1] "structure(c(4, 5), .Names = c(\"a\", \"b\"))" ""                                            
[3] "2L]]"  

11
deparse(quote(var))

我的直观理解是,引号冻结了求值中的var或表达式,而deparse函数是parse函数的逆函数,使冻结的符号返回到String


6

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

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 shows 
#"structure(list(a = 1, b = 2), .Names = c(\"a\", \"b\"), class = \"foo\")"
test

我在论坛上看到的其他评论表明,最后的行为是不可避免的。如果您正在为包装编写打印方法,这是很不幸的。


也许应该是:print.foo=function(x){ cat(deparse(substitute(x))) }print.foo=function(x){ print(deparse(substitute(x)), quote=FALSE) }
IRTFM 2013年

1
print.foo=function(x){ print.default(as.list(x)) }
IRTFM 2013年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.