1

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?

socialscientist
  • 3,759
  • 5
  • 23
  • 58
PaddyN
  • 13
  • 3
  • 1
    Apologies if I haven't made this clear enough in the original post but the issue isn't creating the empty dataframe (which seems to be the question being asked in the linked post). Instead, the question is specifically how do I pass the names of the columns as arguments in a custom function which creates the empty dataframe . – PaddyN Jul 25 '22 at 01:24
  • @ZheyuanLi it's not just making a new `data.frame` if you read what they're looking for. I'll edit the title some to help them. @PaddyN I've proposed two solutions below. Usually in your question you want to provide all of the information you can about (a) what you're passing to the function (i.e., give us info about `a` and `b` by creating an example) and (b) expected output. – socialscientist Jul 25 '22 at 01:26
  • Thanks for the clarification. I'll make sure to include some more context in further questions! – PaddyN Jul 25 '22 at 01:30

1 Answers1

0

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)
socialscientist
  • 3,759
  • 5
  • 23
  • 58