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)

  • Try with `<<-` operator – akrun Dec 12 '18 at 12:17
  • 3
    It’s possible but **strongly discouraged**. Functions that modify global scope are an anti-pattern. Instead, you need to change the data access logic of your code to make this unnecessary. – Konrad Rudolph Dec 12 '18 at 12:27

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
  • 530,221
  • 131
  • 937
  • 1,214
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
  • 874,273
  • 37
  • 540
  • 662