Home > OS >  How to change a variable name into a single vector containing that name?
How to change a variable name into a single vector containing that name?

Time:12-24

I am using R and I want to change this:

variablename

to this

c("variablename")


I want to use the vector for a function that looks like this:

function.describe <- function(data,variablename){
...
a<-data[c("variablename")]%>%
summary()

return(a)
}

My goal is to insert only the variablename and the dataset to get the summary. I do not want to insert a vector into the function. What do I have to add instead of the three dots?

CodePudding user response:

In base R, use substitute with deparse to convert the unquoted argument to character

function.describe <- function(data,variablename){
      variablename <- deparse(substitute(variablename))
  data[variablename]%>%
          summary()


}

-testing

> function.describe(iris, Species)
       Species  
 setosa    :50  
 versicolor:50  
 virginica :50  

Or if we want to use dplyr, select with {{}}

function.describe <- function(data, variablename) {
      data %>%
           select({{variablename}}) %>%
           summary()
}

-testing

> function.describe(iris, Species)
       Species  
 setosa    :50  
 versicolor:50  
 virginica :50  
  • Related