Search code examples
rplyrsumifsdplyr

Creating a function to return a column


I need to create a function to return a column given in to the function as an argument. Eg

fun = function (parameter) {
result = get(paste0("dataframe","parameter"))
return(result) }

so that if I would use fun (columnnamethatexists) it would return dataframe$columnnamethatexists

Currently, what it does is return dataframe$parameter does not exist, no matter what I put in as input.

Sorry for a stupid Q which is probably a replicate, yet I could not find it.

Thanks!


Solution

  • dataframe <- data.frame(a = 1:10, b = LETTERS[1:10])
    
    fun <- function(val) {
      dataframe[, val]
    }
    
    fun("a")
    #  [1]  1  2  3  4  5  6  7  8  9 10
    fun("b")
    #  [1] A B C D E F G H I J
    # Levels: A B C D E F G H I J