Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make a custom function that builds an empty dataframe with specific column names in R

I’m wanting to create a function that produces an empty dataframe, where the columns are passed as arguments in the function. My current attempt looks like this:

create_df<-function(column1, column2){
  df <- data.frame(column1=character(),
             column2=numeric(),
             stringsAsFactors = FALSE)
}
df <- create_df(a,b)

While this code succeeds in creating an empty data.frame, the column names are column1 and column2 rather than a and b. Is there a straightforward way to fix this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Depending upon what you want a and b to be, you could use either of the below:

Example inputs to function

a <- "foo"
b <- "bar"

Option 1: Function that gets column names from object values

create_df_string <- function(column1, column2) {
  df <- data.frame(temp1 = character(),
                   temp2 = numeric(),
                   stringsAsFactors = FALSE)
  
  colnames(df) <- c(column1, column2)
  
  return(df)
  
}

Option 2: Function that gets column names from object name

create_df_string(a, b)
#> [1] foo bar
#> <0 rows> (or 0-length row.names)

create_df_obj <- function(column1, column2) {
  df <- data.frame(temp1 = character(),
                   temp2 = numeric(),
                   stringsAsFactors = FALSE)
  
  colnames(df) <- c(deparse(substitute(column1)),
                    deparse(substitute(column2)))
  
  return(df)
  
}

create_df_obj(a, b)
#> [1] a b
#> <0 rows> (or 0-length row.names)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading