# NOT RUN {
# Example 1:
# This example shows the difference between using get_obj_name() and deparse(substitute())
g <- function(y) { return(list(obj_name=get_obj_name(y, n=2, silent=FALSE),
substitute=deparse(substitute(y, parent.frame(n=2))) )) }
f <- function(x) { g(x) }
z = 3;
f(z) # After showing the names of objects as they
# are traversed in the parameter chain (silent=FALSE),
# this function returns a list where
# the first element (result of get_obj_name()) is "z"
# and the second element (result of deparse(substitute())) is "y".
# Note that 'z' is the object leading to object 'y'
# inside function g() if we follow the parameter names
# leading to 'y' in the function calling chain.
# Example 2:
# When eval=TRUE, get_obj_name() behaves the same way as deparse()
# (except for the cases noted in the Details section)
# because the values of all objects linked by the parameter chain
# are ALL the same.
g <- function(y) { return(list(obj_name=get_obj_name(y, n=2, eval=TRUE),
deparse=deparse(y))) }
f <- function(x) { g(x) }
z = 3
f(z) # Returns a list where both elements are equal to "3"
# because the output of get_obj_name() with eval=TRUE
# and deparse() are the same.
# Example 3:
# This example shows how we can use get_obj_name() to get the parameter names
# of non '...' parameters, which are then used in messages to the user.
# The advantage of using get_obj_name() as opposed to the hard-coded parameter name
# is that an error is raised if the parameter does not exist.
# An example is also shown that uses as.list(environment()), which clearly is more
# general... get_obj_name() should be used when referring to a couple of specific
# parameters.
f <- function(x, y, ...) {
cat("Arguments received by the function (using get_obj_name()) (explicit listing):\n")
cat(get_obj_name(x), ":", x, "\n")
cat(get_obj_name(y), ":", y, "\n")
cat("Arguments received by the function (using as.list(environment())) (automatic listing):\n")
paramsList = as.list(environment())
paramsNames = names(paramsList)
sapply(paramsNames, get_obj_name)
for (p in paramsNames) {
cat(p, ":", paramsList[[p]], "\n")
}
}
z = 5
extra_param = "a '...' parameter"
## Note: this exra parameter is NOT shown neither by get_obj_name()
## nor by as.list(environment())
f("test", z, extra_param)
# }
Run the code above in your browser using DataLab