在 R 中,如何在将对象发送给函数后获取对象的名称? [英] In R, how to get an object's name after it is sent to a function?
问题描述
我正在寻找 get()
的反面.
I am looking for the reverse of get()
.
给定一个对象名称,我希望直接从对象中提取代表该对象的字符串.
Given an object name, I wish to have the character string representing that object extracted directly from the object.
foo
是我正在寻找的函数的占位符的简单示例.
Trivial example with foo
being the placeholder for the function I am looking for.
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")
推荐答案
旧的 deparse-substitute 技巧:
The old deparse-substitute trick:
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"-属性和处理顺序.
Note: this will not succeed inside a local function when a set of list items are passed from the first argument to lapply
(and it also fails when an object is passed from a list given to a for
-loop.) You would be able to extract the ".Names"-attribute and the order of processing from the structure result, if it were a named vector that were being processed.
> lapply( list(a=4,b=5), function(x) {nm <- deparse(substitute(x)); strsplit(nm, '\[')} )
$a # This "a" and the next one in the print output are put in after processing
$a[[1]]
[1] "X" "" "1L]]" # Notice that there was no "a"
$b
$b[[1]]
[1] "X" "" "2L]]"
> lapply( c(a=4,b=5), function(x) {nm <- deparse(substitute(x)); strsplit(nm, '\[')} )
$a
$a[[1]] # but it's theoretically possible to extract when its an atomic vector
[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]]"
这篇关于在 R 中,如何在将对象发送给函数后获取对象的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!