R: Rosts Names, Names, Names and Names

I would like to use apply to run through the rows of the matrix, and I would like to use the name rowname of the current row in my function. It seems you cannot use rownames , colnames , dimnames or names directly inside a function. I know that I may be creating a workaround based on the information in this question .

But my question is, how do apply process the names of the rows and columns of the array in it with the first argument and naming the objects created inside the function called apply ? This seems a little inconsistent, as I hope to show in the following example. Is there a reason why it was designed like this?

 # Toy data m <- matrix( runif(9) , nrow = 3 ) rownames(m) <- LETTERS[1:3] colnames(m) <- letters[1:3] m abc A 0.5092062 0.3786139 0.120436569 B 0.7563015 0.7127949 0.003358308 C 0.8794197 0.3059068 0.985197273 # These return NULL apply( m , 1 , FUN = function(x){ rownames(x) } ) NULL apply( m , 1 , FUN = function(x){ colnames(x) } ) NULL apply( m , 1 , FUN = function(x){ dimnames(x) } ) NULL # But... apply( m , 1 , FUN = function(x){ names(x) } ) ABC [1,] "a" "a" "a" [2,] "b" "b" "b" [3,] "c" "c" "c" # This looks like a column-wise matrix of colnames, with the rownames of m as the column names to me # And further you can get... n <- apply( m , 1 , FUN = function(x){ names(x) } ) dimnames(n) [[1]] NULL [[2]] [1] "A" "B" "C" # But you can't do... apply( m , 1 , FUN = function(x){ n <- names(x); dimnames(n) } ) NULL 

I just want to understand what is happening inside of me? Thank you very much.

+4
source share
1 answer

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 line itself is a "only" (named) vector:

 > m[1,] abc 0.48768161 0.61447934 0.08718875 

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

For your average example, as described in apply :

If each FUN call returns a vector of length n, then apply a return array of dimension c (n, dim (X) [MARGIN]), if n> 1. If n is 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 end result is the matrix you see. But this matrix is ​​built at the end of the apply function, and the FUN results are applied to each row separately.

+8
source

All Articles