Pretty simple question.
Is there a way to avoid simplification in
apply()?
I need to do it because I have an apply which can sometimes simplify (and it does it) and sometimes not, thus creating different data structures depending on the input, so I want to avoid it altogether.
I need either something similar to SIMPLIFY = FALSE in mapply() or a mechanism to control output as the one in vapply().
Simple reproducible example:
mimat <- matrix(c(1,2,3,4,5,6), nrow = 2)
mimat2 <- matrix(c(3,2,3,4,5,6), nrow = 2)
apply(mimat, MARGIN = 2, function(x) { 
                              if (is.element(el = 1, x)) return(c(0,1))
                              else return(c(1,2,3))
      })
If the apply() is applied to mimat it outputs a list, whereas if it is applied to mimat2 it outputs a matrix.
R4.1.0 added a simplify argument to apply() on 2021-03-06.
With older versions of R, the best option is probably
lapply(seq_len(dim(minat)[2]), YourFunction)
                        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