# [R] labels

Barry Rowlingson B.Rowlingson at lancaster.ac.uk
Tue Apr 29 18:26:41 CEST 2003

```Anna H. Pryor wrote:
> I don't know how to retain my row labels.  I read in a table with row labels,
> ie:
>
> Price   Floor  Area  Rooms
> 52.      111.   830    5
> 54.      128.   710    5
> 47.4    101   1000   4

I dont see any row labels. I assume you mean column labels!

>
> but then I need to transform the data
>
> raggedRidzeros <- function(x){
>
> 	y = list(ridzeros(x[[1]]))
> 	for(i in 2:length(x)){
> 	  y = c(y,list(ridzeros(x[[i]])))
> 	}
> 	y
>
> }

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

```