Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid simplification in apply()

Tags:

r

apply

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.

like image 449
D1X Avatar asked Oct 16 '22 10:10

D1X


1 Answers

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)
like image 178
Martin Smith Avatar answered Oct 20 '22 23:10

Martin Smith