Why is the R function confusing rows with columns used?

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 printing is performed differently another time on the column. Why is that? In my opinion, both apply / print calls should do the same.

+6
source share
1 answer

Two things can be distinguished here: what printprints and what returns.

The method printfor a numeric vector will print the contents of the vector on the screen. This is the first part of your result:

[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.

print , ; . ( ) . apply, . apply :

          [,1]      [,2]
[1,] 0.8966972 0.2655087
[2,] 0.3721239 0.5728534
[3,] 0.9082078 0.2016819

? , apply. ?apply:

FUN n, apply c (n, dim (X) [MARGIN]), n > 1. n 1, apply , MARGIN 1 dim (X) [MARGIN] .

+6

Source: https://habr.com/ru/post/1016648/


All Articles