8

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

smci
  • 32,567
  • 20
  • 113
  • 146
AP30
  • 505
  • 7
  • 18
  • 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 Nov 27 '17 at 22:46

2 Answers2

4

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
Andrew Gustar
  • 17,295
  • 1
  • 22
  • 32
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
acylam
  • 18,231
  • 5
  • 36
  • 45