[R] labels

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Tue Apr 29 18:44:38 CEST 2003


Barry Rowlingson <B.Rowlingson at lancaster.ac.uk> writes:

>   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 :)

...but slightly dangerous if you have a risk of ending up with all
lists elements equally long, because then you get a matrix instead of
a list. If you want to make damn sure that you get a list, I think you
need something like

do.call("c",apply(tm,2,function(x)list(x[x!=0]))

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907



More information about the R-help mailing list