Search code examples
rdataframenaming

How to set column name in dataframe from function in R


I want to create an empty dataframe in R in such a way that the column name is defined as an input parameter of a function like this:

testfunc <- function(columname){
  print(data.frame(columname=NA))
}

testfunc('hello')

However when i run the function what i get is something like this:

> testfunc('hello')
  columname
1        NA

as you can see the column name is columname instead of hello. What is it wrong with my code? What should it do in order to get as an output a dataframe with the column named as the input string of the function?


Solution

  • Try creating an empty data frame in the function, and then manually assign the column names you want:

    testfunc <- function(columname) {
        df <- data.frame(col=character())
        names(df) <- columname
        return(df)
    }
    

    Of course, then you would have an empty data frame, which means you would need to use something like rbind to add new rows.

    The reason your current approach won't work is that you are actually assigning the name columname to the single column in your data frame. If you want to use a dynamic string name, then you will have to access names() or something similar.