[R] Assigning labels to a list created with apply

John Kane jrkrideau at yahoo.ca
Fri Feb 2 14:00:40 CET 2007


I have a simple data base and I want to produce tables
for each variable.  I wrote a simple function
 fn1 <- function(x) {table(x)}  where x is a matrix or
data.frame. and used apply to produce a list of
tables. Example below.

How do I apply the colnames from the matrix or names
from the data.frame to label the tables in the results
in the list.  I know that I can do this individually
but there should be a way to do something like an
apply but I am missing it

cata <- c( 1,1,6,1,1,NA)
catb <- c( 1,2,3,4,5,6)
doga <- c(3,5,3,6,4, 0)
dogb <- c(2,4,6,8,10, 12)
rata <- c (NA, 9, 9, 8, 9, 8)
ratb <- c( 1,2,3,4,5,6)
bata <- c( 12, 42,NA, 45, 32, 54)
batb <- c( 13, 15, 17,19,21,23)
id <- c('a', 'b', 'b', 'c', 'a', 'b')
site <- c(1,1,4,4,1,4)
mat1 <-  cbind(cata, catb, doga, dogb, rata, ratb,
bata, batb)

fn1 <- function(x) {table(x)}
jj <-apply(mat1, 1, fn1) ; jj

##  Slow way to label a list ###
label(jj[[1]]) <- "cata"
label(jj[[2]]) <- "catb"

#  and so on ...



More information about the R-help mailing list