vendredi 20 février 2015

Avoiding If-Then-Else structure in R

The task I'm facing is to return some rows from a list of data frames. Rows to return can be entered as a number or as "first" and "last". I've coded that like this:



showrow <- function(row) {
if (class(row) == "numeric") {
getrow <- function(d) {
d[row,]
}
return(getrow)
} else {
if (row =="first") {
getrow <- function(d) {
head(d, 1)
}
return(getrow)
} else {
if (row == "last") {
getrow <- function(d) {
tail(d, 1)
}
return(getrow)
} else {
stop("invalid position")
}
}
}
}


And then it's possible to use it like that:



a <- matrix(rnorm(20), 4)
b <- matrix(rnorm(100), 10)
lst <- list(a, b) ; lst
num <- "last" # Or `num <- "first"`, or `num <- 3`, etc
lapply(lst, function(df) { showrow(num)(df) })


The problem is I think that If structure still looks clumsy... Is there any workaround to avoid it in this particular scenario?




(And, on a side note, is it possible to return NAs if the subscript would be out of bounds, like num <- 11, for example?)


Aucun commentaire:

Enregistrer un commentaire