Reputation: 814
The following code:
set.seed(0)
m<-matrix(data=runif(6),nrow=2)
apply(m,1,print)
apply(m,1,function(x) print(x) )
gives:
[1] 0.8966972 0.3721239 0.9082078
[1] 0.2655087 0.5728534 0.2016819
[,1] [,2]
[1,] 0.8966972 0.2655087
[2,] 0.3721239 0.5728534
[3,] 0.9082078 0.2016819
So, one time print is executed row-wise the other time column-wise. Why that? In my understanding the both calls to apply/print should do exactly the same thing.
Upvotes: 6
Views: 76
Reputation: 57686
There are two things to distinguish here: what print
prints, and what it returns.
The print
method for a numeric vector will print the contents of the vector to the screen. This is the first part of the output you got:
[1] 0.8966972 0.3721239 0.9082078
[1] 0.2655087 0.5728534 0.2016819
Here, the first row is the printed output for row 1 of your matrix, and the second row is the printed output for row 2.
In addition to this, the print
method is a function, like any other function; it returns a value. The value it returns is (for the default methods) what was passed into it. This returned value is passed back to apply
, as a series of vectors. apply
then concatenates these vectors into a matrix:
[,1] [,2]
[1,] 0.8966972 0.2655087
[2,] 0.3721239 0.5728534
[3,] 0.9082078 0.2016819
Why are the vectors treated as column vectors? Because that's what apply
does. From ?apply
:
Value
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. If n equals 1, apply returns a vector if MARGIN has length 1 and an array of dimension dim(X)[MARGIN] otherwise.
Upvotes: 7