Copy a data frame in a function

Viewed 68

I want to copy data frame a to a new data frame b inside a function.

a <- mtcars

saveData <- function(x, y){
    y <- x
    return(y)
}

saveData(a, b)

In this example, the function should create the object/data frame b. b should be a copy of a (i.e., mtcars)

The crux is to flexibly "name" objects.

I excessively played around with assign(), deparse(), and substitute(), but I could not make it work.

2 Answers

It is not a good pracrtice to save the data in global environment from a function. However if you want to do it here is a way :

saveData <- function(x, y){
   assign(deparse(substitute(y)), x, envir = parent.frame())
}

a <- mtcars
b

Error: object 'b' not found

saveData(a, b)
b
#                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
#Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
#Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
#Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
#Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
#Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
#...

Another idea is to use list2env, but you have to convert to a named list, so your second argument will need to be a character, i.e.

saveData <- function(x, y) {
     v1 <- setNames(list(x), y)
     list2env(v1, envir = .GlobalEnv)
 }

saveData(a, 'b')

b
#                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
#Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
#Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
#Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
#Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
#Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
#.....

NOTE: I wouldn't recommend adding staff to your global environment. It is better to keep them in lists

Related