how to acess global variable in function of r

Here I am using data frame temp as global variable by using "<<- " symbol.I expected to get value global variable value changes affect in every function.but it not working.

my code is

vf<-function()
{
  df<<-data.frame(A=c(2),B=c(3))
  vk(df)
  print(df)
}

vk<-function(df)
{
  lk<-data.frame(C=c(3),D=c(4))
  df<<-cbind(df,lk)
}

nothing happened after function call.

expected output is

>vf()
A  B C D
2  3 3 4

how to fix it ?

Answers


Actually, your code works perfectly :-) The only part you miss if you want to use a global variable, you must declare it globally.

Here's my output:

> df <- NULL
> vf <- function()
{
  df <<- data.frame(A=c(2),B=c(3))
  vk(df)
  print(df)
}
> vk <- function(df)
{
  lk <- data.frame(C=c(3),D=c(4))
  df <<- cbind(df,lk)
}
> vf()
  A B C D
1 2 3 3 4

So what you miss is to add a df <- NULL declaration


You can do the same w/o a global variable, it's a bit cleaner:

vf <- function()
{
  df <- data.frame(A=c(2),B=c(3))
  vk(df) # Same as 'return(vk(df))'
}

vk <- function(df)
{
  lk <- data.frame(C=c(3),D=c(4))
  cbind(df,lk) # Same as 'return(cbind(df,lk))'
}

vf() # Returns value, not stored --> printed on the output
newGlobal <- vf() # Stores the value returned by vf()

By the way, if you interested in R, you can find a list of great books about common snippets and traps here:

http://xcafebabe.blogspot.hu/2011/09/free-r-book-collection.html


Need Your Help

arraylist sorting in order

java sorting arraylist collections

Attempting to sort arraylist in alphabetical order but the Collection.sort is giving me an error which i do not what to do with it

python: how to terminate a thread when main program ends

python multithreading python-multithreading

If I have a thread in an infinite loop, is there a way to terminate it when the main program ends (for example, when I press Ctrl+C)?