Skip to content
Prev 319037 / 398506 Next

Unexpected behaviour of apply()

This is nice fodder for 'The R Inferno' -- thanks.

As Milan said, 'which' will suffice as the function.

Here is a specialized function that only returns a
list and is only implemented to work with matrices.
It should solve your current dilemma.

applyL <-
function (X, MARGIN, FUN, ...)
{
         stopifnot(length(dim(X)) == 2, length(MARGIN) == 1)

         FUN <- match.fun(FUN)
         ans <- vector("list", dim(X)[MARGIN])
         if(MARGIN == 1) {
                 for(i in seq_along(ans)) {
                         ans[[i]] <- FUN(X[i,], ...)
                 }
         } else {
                 for(i in seq_along(ans)) {
                         ans[[i]] <- FUN(X[,i], ...)
                 }
         }
         names(ans) <- dimnames(X)[[MARGIN]]
         ans
}


Pat
On 08/03/2013 08:29, Pierrick Bruneau wrote: