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

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


慕工程0101907
浏览 447回答 3
3回答

白衣非少年

旧的离场-替代伎俩:a<-data.frame(x=1:10,y=1:10)test<-function(z){&nbsp; &nbsp;mean.x<-mean(z$x)&nbsp; &nbsp;nm <-deparse(substitute(z))&nbsp; &nbsp;print(nm)&nbsp; &nbsp;return(mean.x)}&nbsp;test(a)#[1] "a"&nbsp; &nbsp;... this is the side-effect of the print() call#&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ... you could have done something useful with that character value#[1] 5.5&nbsp; &nbsp;... 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"&nbsp; &nbsp; ""&nbsp; &nbsp; &nbsp;"1L]]"$b$b[[1]][1] "X"&nbsp; &nbsp; ""&nbsp; &nbsp; &nbsp;"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\"))" ""&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;[3] "1L]]"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;$b$b[[1]][1] "structure(c(4, 5), .Names = c(\"a\", \"b\"))" ""&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;[3] "2L]]"&nbsp;&nbsp;

芜湖不芜

deparse(quote(var))根据我的直觉理解,引号会冻结计算中的var或表达式,而离开函数是解析函数的逆函数,这使得冻结的符号返回到字符串。
打开App,查看更多内容
随时随地看视频慕课网APP