Global and Local Variables in R

Global and local variables in R

Variables declared inside a function are local to that function. For instance:

foo <- function() {
bar <- 1
}
foo()
bar

gives the following error: Error: object 'bar' not found.

If you want to make bar a global variable, you should do:

foo <- function() {
bar <<- 1
}
foo()
bar

In this case bar is accessible from outside the function.

However, unlike C, C++ or many other languages, brackets do not determine the scope of variables. For instance, in the following code snippet:

if (x > 10) {
y <- 0
}
else {
y <- 1
}

y remains accessible after the if-else statement.

As you well say, you can also create nested environments. You can have a look at these two links for understanding how to use them:

  1. http://stat.ethz.ch/R-manual/R-devel/library/base/html/environment.html
  2. http://stat.ethz.ch/R-manual/R-devel/library/base/html/get.html

Here you have a small example:

test.env <- new.env()

assign('var', 100, envir=test.env)
# or simply
test.env$var <- 100

get('var') # var cannot be found since it is not defined in this environment
get('var', envir=test.env) # now it can be found

How to make a local variable global in R using Shiny?

Just create the variable outside any sub-function and update its value using <<-. This variable will be global per each session.

server <- function(input, output) {

# init variable here
algorithm_output <- NULL

out_plots <- eventReactive(input$ok_input, {

# to modify a global variable use <<- instead of <- or =
algorithm_output <<- some_global_function(3, 2, 1)

do.call("grid.arrange", c(algorithm_output$indexes, nrow=3))
})

output$indexes <- renderPlot({
out_plots()
})

out_means <- eventReactive(input$ok_means, {
k = as.integer(input$k)

# you can get access to the updated value of your variable
matplot(algorithm_output$means[[k-1]], type = "l", lty=1)

})
output$means <- renderPlot({
out_means()
})
}

How to define 'local' variables in R?

This answers illustrates the use of local within a loop in R:

    number <- 1:5
res <- numeric(5)
local(for(i in number){
res2 <-res[i] + 42
print(res2)
})
[1] 42
[1] 42
[1] 42
[1] 42
[1] 42

The above does not create res2 in .GlobalEnv unlike the following:

 for(i in number){
res2 <-res[i] + 42
print(res2)
}

Alternatively, you could avoid loops and use *apply and/or use functions that use local variables by design. See examples here

Global variables in R

As Christian's answer with assign() shows, there is a way to assign in the global environment. A simpler, shorter (but not better ... stick with assign) way is to use the <<- operator, ie

    a <<- "new" 

inside the function.

R function wont modify global variable

I think I know what is wrong

Change data <- table to data <<- table within your function

You are assigning the result to the local environment for the function, whilst the <<- will be assigning it to the global environment.

I would propose you try the following

library(rvest)
getData <- function(url) { html_table(read_html(url)) }

data <- getData("https://steemdb.com/accounts/reputation?page=1")

Or even better

library(rvest)
getData <- function(url) { html_table(read_html(url)) }
steemdb.url <-"https://steemdb.com/accounts/reputation?page="

data <- lapply(1:100, function(i) getData(paste0(steemdb.url, i)) )
data <- do.call(rbind, data)
View(data)

1:100 will get you the first 100 pages.

R global and local variable from loops

changing the line

b<<-a

into

b<<- get0("a", envir= parent.frame() )

should do it. However, please take note of Gregor's comment and see if this is really what you want.

Cant manipulate global/local variables inside a function in R

You forgot the dnastring <-

dna = c("A","G","C","T")

x =sample(dna,50,replace =TRUE)


dna_f = function(x){
dnastring <- ""
for (val in x){
dnastring <- paste(dnastring,val,sep="")

}
return(dnastring)

}

Output:

> dna_f(x)
[1] "GGTCTGGCCGAACTACTGTACACCCCAAAGACAACGCCCCCGACGCTCTA"

Using global variable in function

Both <<- and assign will work:

myfunction <- function(var1, var2) {
# Modification of global mydata
mydata <<- ...
# Alternatively:
#assign('mydata', ..., globalenv())

# Assign locally as well
mydata <- mydata

# Definition of another variable with the new mydata
var3 <- ...

# Recursive function
mydata = myfunction(var2, var3)
}

That said, it’s almost always a bad idea to want to modify global data from a function, and there’s almost certainly a more elegant solution to this.

Furthermore, note that <<- is actually not the same as assigning to a variable in globalenv(), rather, it assigns to a variable in the parent scope, whatever that may be. For functions defined in the global environment, it’s the global environment. For functions defined elsewhere, it’s not the global environment.



Related Topics



Leave a reply



Submit