how do i refer to columns in a function?

If you want to use [ to select column version 1 would work without toString :

function_x <- function(dataframe,columnname) {
  sum(dataframe[, columnname])
}

function_x(test, "numbers")
#[1] 10

You cannot directly pass unquoted variables (version 2) to select columns.

function_x <- function(dataframe,columnname) {
  cols <- deparse(substitute(columnname))
  sum(dataframe[, cols])
}

function_x(test, numbers) 
#[1] 10

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top