0

To improve speed i create some general global data set that are always available. From time to time they need to be updated.

I am trying to do this in a function that i will call when the dataset needs to be updated.

Is there any way you can create a global dataset in a function in R? I am aware of the assign function, but I cannot get the function to work for a dataframe, only a variable.

How do i do that?

x <- c(1,2,3,4)

z <- function ()  x <- c(1,2,3,4,5,6,7,8,9,10)  

now when i run z(), it should update x to (1...10)

2 Answers2

3

I am aware of the assign function, but I cannot get the function to work for a dataframe, only a variable.

Odd: assign works the same way for all types of objects, regardless of their type:

assign('name', object, environment)

In your case, this would be:

assign('x', your_df, globalenv())

— But as mentioned in a comment, modifying objects outside the function’s scope is a very bad idea (there are very few exceptions). The correct way for your function to work is to return the modified/created object from the function.

To use your example:

x <- c(1,2,3,4)

z <- function () c(1,2,3,4,5,6,7,8,9,10)

# Usage:

x <- z()
Konrad Rudolph
  • 506,650
  • 124
  • 909
  • 1,183
1

We can use the <<- operator for assigning variables globally

z <- function ()  x <<- c(1,2,3,4,5,6,7,8,9,10) 
z()
x
#[1]  1  2  3  4  5  6  7  8  9 10
akrun
  • 789,025
  • 32
  • 460
  • 575