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

1
  • 2
    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).
    – MrFlick
    Commented Nov 27, 2017 at 22:46

3 Answers 3

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
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
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)
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.