## 在R中，如何在对象被发送到函数后获得它的名称？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (33)

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

### 2 个回答

``````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( 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]]"
``````

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