Reputation: 21
I want to return a specific variable from a function, but this variable is unused, so for example:
fx <- function(x) { z <- 39 }
I tried it with the get function but i didnt get the value, maybe there is an easier solution to this. How can I return ´z` from this function?
Upvotes: 0
Views: 117
Reputation: 2301
It is not clear to me what you want to do. If you want to add the variable z
with a value to the global environment, using a function, the <<-
operator does that. E.g.
fx <- function(x){(z <<- x)}
fx(39)
[1] 39
With the variable z
created in the global environment with the value of 39. However using the <<-
operator inside of a function is not recommended. Rather assign a global variable to the return value of the function. E.g.:
fx <- function(x){(retVal <- x)}
z <- fx(39)
z
[1] 39
Upvotes: 2
Reputation: 269654
Normally one does not want to directly inject variables into the caller but rather we prefer to return it as the value of the function but assuming you really need this:
fx <- function(envir = parent.frame()) invisible(assign("z", 39, envir))
fx()
z
## [1] 39
Upvotes: 2