我正在寻找相反的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)
Run Code Online (Sandbox Code Playgroud)
会打印:
"z"
Run Code Online (Sandbox Code Playgroud)
我的工作,在我目前的问题中更难实现的是:
test <- function(a="z"){
mean.x <- mean(get(a)$x)
print(a)
return(mean.x)}
test("z")
Run Code Online (Sandbox Code Playgroud)
42-*_*42- 144
旧的解密替代技巧:
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
Run Code Online (Sandbox Code Playgroud)
编辑:使用新的测试对象进行操作
注意:当一组列表项被传递给本地函数时,这将不会成功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]]"
Run Code Online (Sandbox Code Playgroud)
deparse(quote(var))
Run Code Online (Sandbox Code Playgroud)
我的直觉理解,其中引号冻结了评估中的var或表达式,而deparse函数是parse函数的逆函数,使冻结的符号返回到String
请注意,对于打印方法,其行为可能有所不同。
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
Run Code Online (Sandbox Code Playgroud)
我在论坛上看到的其他评论表明,最后的行为是不可避免的。如果您正在为包装编写打印方法,这是很不幸的。