Use function argument as name for new data frame in R
Asked Answered
D

3

9

this is very simple, but I have searched and failed to find a solution for this small problem.

I want to use the argument of a function as the name for a new data frame, for example:

assign.dataset<-function(dataname){
    x<-c(1,2,3)
    y<-c(3,4,5)
    dataname<<-rbind(x,y)
}

Then

assign.dataset(new.dataframe.name)

just creates a new dataset with the name dataname.

I have tried to use the paste and assign functions but with no success.

Many thanks

Distiller answered 27/11, 2017 at 17:46 Comment(1)
This not a good way to do things in R. While technically possible, functions should not create variables outside of their own scope. Consider something more like dataname <- create_dataset() where create_dataset() just returns rbind(x,y).Prediction
D
5

You can do it like this...

assign.dataset<-function(dataname){
  x<-c(1,2,3)
  y<-c(3,4,5)
  assign(deparse(substitute(dataname)), rbind(x,y), envir=.GlobalEnv)
}

assign.dataset(new.dataframe.name)

new.dataframe.name
  [,1] [,2] [,3]
x    1    2    3
y    3    4    5
Dreibund answered 27/11, 2017 at 17:53 Comment(0)
B
3

Here is the rlang equivalent to @Andrew's answer:

library(rlang)

assign.dataset<-function(dataname){
  x<-c(1,2,3)
  y<-c(3,4,5)
  assign(quo_name(enquo(dataname)), rbind(x,y), envir=.GlobalEnv)
}

assign.dataset(test_df)

enquo captures the argument provided by the user and bundles it with the environment which the function was called into a quosure. quo_name then converts the quosure into a character.

However, I would advice against doing this instead of assigning the output of your function to an object. The following is how I would do it:

assign.dataset<-function(){
  x<-c(1,2,3)
  y<-c(3,4,5)
  rbind(x,y)
}

test_df = assign.dataset()

Result:

  [,1] [,2] [,3]
x    1    2    3
y    3    4    5
Benitabenites answered 27/11, 2017 at 18:15 Comment(0)
C
0

The above responses still require you to manually give the data.frame a name, just use a function to assign it. This makes little sense...

In my case I had a bunch of csv files to load into data.frames named like the file names. I used simple assign in a loop for this (files vector holds the names of csv files without extension, and path is the folder):

for (i in files) {
  assign(i, read.csv(paste(path, "/", i, ".csv", sep="")), envir=.GlobalEnv)
}
Conchoid answered 15/11, 2023 at 12:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.