[R] Assigning labels to a list created with apply
Prof Brian Ripley
ripley at stats.ox.ac.uk
Fri Feb 2 14:21:46 CET 2007
On Fri, 2 Feb 2007, John Kane wrote:
> 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"
That does not work in vanilla R. There is no function label<- (or label).
Have you a package attached you did not tell us about? (E.g. are you
using the Hmisc system, not the R system?)
You have applied fn1 to the rows and not the columns, and
jj <-apply(mat1, 2, fn1)
would give you the column labels as they do make sense. The way to add
names to a list is names().
--
Brian D. Ripley, ripley at stats.ox.ac.uk
Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/
University of Oxford, Tel: +44 1865 272861 (self)
1 South Parks Road, +44 1865 272866 (PA)
Oxford OX1 3TG, UK Fax: +44 1865 272595
More information about the R-help
mailing list