Output of the sapply function in R

sapply
r

#1

I tried the below code to get the squares of the terms in the matrix format.

x<-matrix(1:9,3)
sapply(x,function(y) y^2)

This returns a single vector of squares

sapply(x,function(y) y^2,simplify = F)

This returns a list where every element is a vector.
I want the original 3x3 matrix. I understand there are easier ways, but I’m trying to understand the apply functions.


#2

use the manual to understand ( yes the R manuals can be very dense :slight_smile: )

https://stat.ethz.ch/R-manual/R-devel/library/base/html/lapply.html

sapply is a user-friendly version and wrapper of lapply by default returning a vector, matrix or, if simplify = “array”, an array if appropriate, by applying simplify2array()