# NOT RUN {
# Example of using get_obj_value() from within a function
# The value returned by get_obj_value() is compared to the values returned by eval() and evalq()
compareResultsOfDiferentEvaluations <- function(x) {
cat("Looking at the path of variables leading to parameter 'x':\n")
xval = get_obj_value(x, n=1, silent=FALSE)
cat("Value of 'x' at parent generation 1 using get_obj_value():", xval, "\n")
cat("Value of 'x' at parent generation 1 using eval():", eval(x, parent.frame(1)), "\n")
cat("Value of 'x' at parent generation 1 using evalq():", evalq(x, parent.frame(1)), "\n")
}
g <- function(y) {
x = 2
compareResultsOfDiferentEvaluations(y)
}
z = 3
g(z)
## Note how the result of get_obj_value() is the same as eval() (=3)
## but not the same as evalq() (=2) because the queried object (x)
## exists in the queried parent generation (g()) with value 2.
## The results of eval() and get_obj_value() are the same but
## obtained in two different ways:
## - eval() returns the value of 'x' in the calling function (even though
## the evaluation environment is parent.frame(1), because eval() first
## evaluates the object in the calling environment)
## - get_obj_value() returns the value of 'y' in the parent generation
## of the calling function (which is the execution environment of g())
## since 'y' is the variable leading to variable 'x' in the calling function.
##
## NOTE however, that using get_obj_value() does NOT provide any new
## information to the result of eval(), since the variable values are
## transmitted UNTOUCHED through the different generations in the
## function calling chain.
## FURTHERMORE, the same value is returned by simply referencing 'x'
## so we don't need neither the use of get_obj_value() nor eval().
## The only interesting result would be provided by the evalq() call
## which looks for variable 'x' at the parent generation and evaluates it.
# Example of calling get_obj_value() from outside a function
x = 3
v = c(4, 2)
get_obj_value(x) # 3
get_obj_value("x") # 3
get_obj_value(3) # 3
get_obj_value(v[1]) # 4
# }
Run the code above in your browser using DataLab