user2543622
user2543622

Reputation: 6756

R global and local variable from loops

I have below code. How could I assign global variable a to b? In below case i want to assign global a (which contains "new") to b. But R assigns local a to b. Moreover is there any way to check value of the global variable with the function? If global a's value is "old" that i want to take some set of actions which are different from actions that i will take if a's value is "new"

a <- "old"
test <- function () {
  a="new1"
  a<<-"new"
  b<<-a
  print(paste("b is ",b))
}
test()

Upvotes: 0

Views: 2593

Answers (1)

R.S.
R.S.

Reputation: 2140

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.

Upvotes: 1

Related Questions