Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a missing argument in R

Tags:

r

I'm writing a function in R that, among other things, subsets a data frame based on a vector of column names. I'm trying to exploit the default behavior of [.data.frame which will return all columns if the 'j' argument is missing. Is there a way to pass a missing argument through my wrapper function? Here's a bare bones example:

fixDataFrames <- function(listOfDataFrames, columns){
    lapply(listOfDataFrames, function(x) x[,columns])
}

If I do not specify a value for columns, I get an error when passing it to the [ function: "columns argument is missing, with no default".

like image 551
Jesse Anderson Avatar asked Jan 13 '23 20:01

Jesse Anderson


1 Answers

You could set a default for columns such that if nothing is supplied it grabs all of the columns. Using TRUE should work

fixDataFrames <- function(listOfDataFrames, columns = TRUE){
    lapply(listOfDataFrames, function(x) x[,columns])
}

# As Chase points out it is probably more prudent to add drop=FALSE as a parameter
fixDataFrames <- function(listOfDataFrames, columns = TRUE, drop = FALSE){
    lapply(listOfDataFrames, function(x) x[, columns, drop = drop])
}
like image 77
Dason Avatar answered Jan 19 '23 12:01

Dason