为了账号安全,请及时绑定邮箱和手机立即绑定

在R中,如何在对象被发送到函数后获得它的名称?

在R中,如何在对象被发送到函数后获得它的名称?

慕工程0101907 2019-07-27 15:15:39
在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)将印刷:  "z"在我目前的问题中,我的工作更难实现:test <- function(a="z"){   mean.x <- mean(get(a)$x)   print(a)   return(mean.x)}test("z")
查看完整描述

3 回答

?
白衣非少年

TA贡献1155条经验 获得超0个赞

旧的离场-替代伎俩:


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-循环如果结构结果是正在处理的命名向量,则可以从结构结果中提取“.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]]"  




查看完整回答
反对 回复 2019-07-29
?
芜湖不芜

TA贡献1796条经验 获得超7个赞

deparse(quote(var))

根据我的直觉理解,引号会冻结计算中的var或表达式,而离开函数是解析函数的逆函数,这使得冻结的符号返回到字符串。


查看完整回答
反对 回复 2019-07-29
  • 3 回答
  • 0 关注
  • 436 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信