Skip to content
Prev 31347 / 398506 Next

labels

Anna H. Pryor wrote:
I dont see any row labels. I assume you mean column labels!
This can all be done in one line! Here's some data that does have row 
and column labels:

 > tm
         Foo       Bar Baz
Mercury   1 0.6961034   0
Venus     2 0.3137058   0
Earth     3 0.7692529   1
Mars      0 0.2598111   0
Jupiter   1 0.8375288   0
Saturn    0 0.5866152   0

  Now I want to sweep through columns and return a list without the 
zeroes. I do this:

 > nonZero <- apply(tm,2,function(x){x[x!=0]})

  and I get a list:

$Foo
Mercury   Venus   Earth Jupiter
       1       2       3       1

$Bar
   Mercury     Venus     Earth      Mars   Jupiter    Saturn
0.6961034 0.3137058 0.7692529 0.2598111 0.8375288 0.5866152

$Baz
Earth
     1

  Note this preserves column names (as the names of the list elements, 
so I can do nonZero$Foo), and keeps the row names (as names of 
individual elements).

 > nonZero$Bar['Earth']
     Earth
0.7692529

  How it works:

   function(x){x[x!=0]}   is my 'ridzeros' function.

  I use 'apply(tm,2,function(x){x[x!=0]})' to apply the ridzeros 
function to columns (thats the '2')  of the matrix. To do the same by 
rows, use '1'.

  Hardly rocket science :)

Baz