Simple inquiry about using sapply in R

2019-07-13 05:50发布

I have a simple, newbie question about sapply in R. My question is about what's happening here:

> sapply(1:5,function(x) matrix(x,2,2))
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    1    2    3    4    5
[3,]    1    2    3    4    5
[4,]    1    2    3    4    5

At first I would have thought this call to sapply would return a five element list, each element of which would have been a 2 x 2 matrix, with the value of the elements in each matrix equal to one of the values in the series passed to sapply. I now see that's exactly what lapply would do here, and I get why -- lapply returns a list, and sapply doesn't. But how does sapply here know to combine the values this way? Meaning, what's going on that causes it to create a single 4 x 5 matrix as its return value? Maybe what I'm asking is what does it mean to "simplify" what would have been the return value of lapply? Thanks for any help anyone can offer.

标签: r sapply
0条回答
登录 后发表回答