3

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?

Community
  • 1
  • 1
Zhubarb
  • 11,432
  • 18
  • 75
  • 114
  • See also https://stat.ethz.ch/pipermail/r-help/2006-January/086064.html and the discussion in http://www.jstatsoft.org/v40/i01 – hadley Aug 19 '13 at 14:55

1 Answers1

8

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
Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
  • 1
    +1, another way would be to return a list and then call `rbind` on it. `do.call(rbind, unlist(apply(data, 1, function(x) list(applyDirichletPrior(x))), rec=FALSE))` – Arun Aug 19 '13 at 11:42
  • I was expecting the function to modify the (2*4) matrix by applying the indicated function at each row and then produce an output with the same dimensions as the input. I understand that apply does not serve this purpose. – Zhubarb Aug 19 '13 at 12:01