r - In a function, is it possible to `return( eval ( expr ) )` -
i trying global assignment within function (e.g. ... <<- ...
), using next code
test_function = function(){ return(eval(parse(text = "test <- 4^2"))) } test_function()
which doesn't assign 16
test
in environment test_function
called.
however
test_function = function(){ return(expression(test <- 4^2)) } eval(test_function())
does!
is there anyway of doing former without resorting latter?
well, careful. if did just
test_function = function(){ test <- 4^2 }
that value not in global environment either, , that's you're doing in first function. note that
test_function = function(){ return(eval(parse(text = "test <- 4^2"))) } print(test_function()) # [1] 16
returns 16 assignment happening in function scope expected , beingness returned. there's no reason think have differently. if want evaluate in parent scope, explicit it
test_function = function(){ return(eval(parse(text = "test <- 4^2"), parent.frame())) } test_function()
or if want operate in global environment, specify that
test_function = function(){ return(eval(parse(text = "test <- 4^2"), globalenv()) } test_function()
but seems poor design decision. it's not polite functions have global side effects that. create sure absolutely necessary application , have no other options.
r
No comments:
Post a Comment