rdataframeassignfunction-parameter

Use function argument as name for new data frame in R


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


Solution

  • 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