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

Time:07-25

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?

CodePudding user response:

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)
  • Related