Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 949
AP30 Avatar asked Nov 27 '17 17:11

AP30


People also ask

How do you name data frames in R?

Method 1: using colnames() method colnames() method in R is used to rename and replace the column names of the data frame in R. The columns of the data frame can be renamed by specifying the new column names as a vector. The new name replaces the corresponding old name of the column in the data frame.

Can a function be an argument in R?

R functions can have many arguments (the default plot function has 16). Function definitions can allow arguments to take default values so that users do not need to provide values for every argument.

Which function can be used to create a data frame in R?

Creating a data frame using Vectors: To create a data frame we use the data. frame() function in R. To create a data frame use data. frame() command and then pass each of the vectors you have created as arguments to the function.

Which of the following is one of the argument of data frame () function?

these arguments are of either the form value or tag = value . Component names are created based on the tag (if present) or the deparsed argument itself. NULL or a single integer or character string specifying a column to be used as row names, or a character or integer vector giving the row names for the data frame.


1 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
like image 151
Andrew Gustar Avatar answered Oct 01 '22 14:10

Andrew Gustar