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.
Apply functions are a family of functions in base R which allow you to repetitively perform an action on multiple chunks of data. An apply function is essentially a loop, but run faster than loops and often require less code.
The apply() family pertains to the R base package and is populated with functions to manipulate slices of data from matrices, arrays, lists and dataframes in a repetitive way. These functions allow crossing the data in a number of ways and avoid explicit use of loop constructs.
In R Programming Language to apply a function to every integer type value in a data frame, we can use lapply function from dplyr package. And if the datatype of values is string then we can use paste() with lapply.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With