Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
How can I assign the result of an operation from within a function to the global environment?
I have a function that which does some calculations. I would like to assign the result of the function to the global environment from within the function, how do I proceed?
A minimal example:
meanFUN <- function(x) {
mean(x, na.rm = TRUE)
}
How can I assign the result from mean(x, na.rm = TRUE)
from within the function to the global environment?
2 answers
In order to assign a variable to the global environment from within a function, there are two ways to proceed: either using the assign operator <<-
or using assign()
.
<<-
comes with the following behaviour: It goes through all environments until it finds the variable in question and replaces it with the current value or creates it anew if it's not found. (Everything run in R 4.0.)
> global_x <- 1
> global_x
[1] 1
> meanFUN <- function(x) {
+ global_x <<- mean(x, na.rm = TRUE)
+ }
> meanFUN(c(1:5))
> global_x
[1] 3
This will create a new variable called global_x
in the global environment from which it can be accessed and global_x
will be changed each time the function is run. However, if global_x
is found in an environment before the global environment, it will be changed there. If we have a function inside a function with the same variable name across different environments and use the <<-
operator, <<-
will only change the first occurrence of the variable in question, so to speak in the overarching local environment of the outer function and not in the global environment.
> global_x <- 1
> global_x
[1] 1
> meanFUN <- function(x) {
+ global_x <- 100
+
+ insideFunction <- function(x) {
+ local_x <- mean(x, na.rm = TRUE)
+ assign("global_x", local_x, envir = .GlobalEnv)
+ print(global_x)
+ }
+
+ print(global_x)
+ insideFunction(x)
+ }
> meanFUN(c(1:5))
[1] 100
[1] 3
> global_x
[1] 1
>
To avoid mistakes while using <<-
, it's better to use assign()
which gives precise control over what is assigned where.
> global_x <- 1
> global_x
[1] 1
> meanFUN <- function(x) {
+ global_x <- 100
+
+ insideFunction <- function(x) {
+ global_x <- mean(x, na.rm = TRUE)
+ assign("global_x", global_x, envir = .GlobalEnv)
+ print(global_x)
+ }
+
+ print(global_x)
+ insideFunction(x)
+ }
> meanFUN(c(1:5))
[1] 100
[1] 3
> global_x
[1] 3
On Stack Overflow is a similar question where it's explained in even greater detail: https://stackoverflow.com/a/10904810/3884967.
You need to assign the result to a variable as follows (pay attention to the double less than sign)
meanFUN <- function(x) { gvar <<- mean(x, na.rm = TRUE) }
1 comment thread