Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R get data.frame name in the function

I wrote a function which does analysis with data.frame. In the function start, I print information what variables are taken in the function. So I want to print info of data.frame name which is used.

But I can not get data.frame name printed. It does not print the data.frame name, instead it prints its content, but not name. is it possible to print the name of data.frame which is passed to function internally in the function.

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)

The output. For the last 2 examples I want to be printed:

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

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

But I get:

> 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
> 
like image 477
K.I. Avatar asked Sep 25 '26 18:09

K.I.


1 Answers

deparse(substitute()) returns you the name of a variable, you can call it like this in your function:

DF <- data.frame(c(1,2)); print(paste("DF", deparse(substitute(DF)),sep="="))
like image 71
David Go Avatar answered Sep 28 '26 09:09

David Go



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!