[R] Tracing a variable name back

Davis, Brian Brian.Davis at uth.tmc.edu
Fri Mar 6 17:22:46 CET 2015


I'm looking to find a way to trace back the original variable name after a being passed through a series of functions.

I can get the variables names for the current call easy enough with match.call, but I'd like to go back further if the function was called from another function.

Say I have.

df <- data.frame(x=1:3, y=c("A", "B", "C"))

check_stuff <- function(x, cn) {
  cl <- match.call()
  df_name <- as.character(as.list(cl)$x)
  cn_name <- as.character(as.list(cl)$cn)
  
  print(df_name)
  print(cn_name)
}


foo <- function(p1, p2) {
  check_stuff(p1, p2)
}

bar <- function(x1, x2) {
  foo(x1, x2)
}

> check_stuff(df, "y")
[1] "df"
[1] "y"

> foo(df, "y")
[1] "p1"
[1] "p2"

> bar(df, "y")
[1] "p1"
[1] "p2"


I'd like foo(df, "y")  and bar(df, "y") to print "df" and "y" from check_type

Any advice on how to achieve this?

Thanks in advance,


Brian Davis



More information about the R-help mailing list