繁体   English   中英

R在函数中获取data.frame名称

[英]R get data.frame name in the function

我写了一个用data.frame进行分析的函数。 在函数启动中,我打印了函数中采用了哪些变量的信息。 所以我想打印使用的 data.frame 名称的信息。

但我无法打印 data.frame 名称。 它不打印 data.frame 名称,而是打印其内容,但不打印名称。 是否可以打印在函数内部传递给函数的 data.frame 的名称。

tmpFuction <- function(DF){

print("#############")
print("tmpFuction starts")
print(paste("DF",DF,sep="="))
print("#############")
return(1)
}
df1 <- data_frame(id=seq(1:4),x=rep(0,4))
df2 <- data_frame(id=c(1,2),x=c(0,4))
tmpFuction(10)
tmpFuction("a")
tmpFuction(df1)
tmpFuction(df2)

输出。 对于我想打印的最后两个示例:

[1] "#############"
[1] "tmpFuction starts"
 [1] "DF=df1"
[1] "#############"

[1] "#############"
[1] "tmpFuction starts"
 [1] "DF=df2"
[1] "#############"
[1] 1
> 

但我得到:

> tmpFuction(10)
[1] "#############"
[1] "tmpFuction starts"
[1] "DF=10"
[1] "#############"
[1] 1
> tmpFuction("a")
[1] "#############"
[1] "tmpFuction starts"
[1] "DF=a"
[1] "#############"
[1] 1
> tmpFuction(df1)
[1] "#############"
[1] "tmpFuction starts"
[1] "DF=1:4"           "DF=c(0, 0, 0, 0)"
[1] "#############"
[1] 1
> tmpFuction(df2)
[1] "#############"
[1] "tmpFuction starts"
[1] "DF=c(1, 2)" "DF=c(0, 4)"
[1] "#############"
[1] 1
> 

deparse(substitute()) 返回一个变量的名称,你可以在你的函数中这样调用它:

DF <- data.frame(c(1,2)); print(paste("DF", deparse(substitute(DF)),sep="="))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM