Use function argument as name for new data frame in R

Viewed 5714

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

2 Answers

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

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
Related