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".
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])
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With