R: rownames, colnames, dimnames and names in apply

后端 未结 1 1549
旧巷少年郎
旧巷少年郎 2021-01-02 11:19

I would like to use apply to run across the rows of a matrix, and I would like to use the rowname of the current row in my function. It seems you can\'t use rownames

相关标签:
1条回答
  • 2021-01-02 11:26

    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.

    0 讨论(0)
提交回复
热议问题