Results transposed with R apply [duplicate]

2019-01-15 20:27发布

问题:

This question already has an answer here:

  • Why apply() returns a transposed xts matrix? 1 answer

Apologies, I just realised that this has already been answered here.

This should be pretty basic but I do not really understand why it is happening. Can someone help? This is the simple code with the example 'data':

applyDirichletPrior <- function (row_vector) {
  row_vector_added <- row_vector + min (row_vector)
  row_vector_result <- row_vector_added / sum(row_vector_added)
}
data <- matrix(c(1,2,3,4,5,6,7,8), nrow=2, ncol=4)
applied <- apply(data, 1, function(x) applyDirichletPrior(x))

The output is given as:

> applied
     [,1]      [,2]
[1,]  0.1 0.1428571
[2,]  0.2 0.2142857
[3,]  0.3 0.2857143
[4,]  0.4 0.3571429

Whereas I expect an output in the same format as the input data, like:

> applied
          [,1]      [,2]      [,3]      [,4]
[1,] 0.1000000 0.2000000 0.3000000 0.4000000
[2,] 0.1428571 0.2142857 0.2857143 0.3571429

Why and at what stage during apply is the transpose happening?

回答1:

Combining the results of the individual apply steps is somewhat arbitrary. On what basis was your expectation different? The behaviour you see is how the documentation describes it:

If each call to ‘FUN’ returns a vector of length ‘n’, then ‘apply’ returns an array of dimension ‘c(n, dim(X)[MARGIN])’ if ‘n > 1’.

Note that you can easily perform the transpose afterwards:

> t(applied)
          [,1]      [,2]      [,3]      [,4]
[1,] 0.1000000 0.2000000 0.3000000 0.4000000
[2,] 0.1428571 0.2142857 0.2857143 0.3571429