R: rownames, colnames, dimnames and names in apply

拈花ヽ惹草 提交于 2019-11-30 13:49:33

I think your confusion stems from the fact that apply does not pass an array (or matrix) to the function specified in FUN.

It passes each row of the matrix in turn. Each row is itself "only" a (named) vector:

> m[1,]
         a          b          c 
0.48768161 0.61447934 0.08718875 

So your function has only this named vector to work with.

For your middle example, as documented in apply:

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.

So function(x) names(x) returns a vector of length 3 for each row, so the final result is the matrix you see. But that matrix is being constructed at the end of the apply function, on the results of FUN being applied to each row individually.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!