[R] Trying to get an apply to work with a list in applying names totables
Marc Schwartz
marc_schwartz at comcast.net
Wed Feb 21 17:38:58 CET 2007
I might suggest an alternative, since you seem to be creating the
underlying data set from scratch.
Create the data frame with the requisite data structures to start with
and then perform the table operations:
# First create your vectors as factors. See ?factor
aa <- factor(c(2,2,1,1,2), levels = 1:2, labels = c("yes", "no"))
bb <- factor(c(5,6,6,7,4), levels = 4:7, labels = letters[1:4])
# Now create your data frame using the names you want for each column
cc <- data.frame(abby = aa, billy = bb)
Now run the table on each column:
> lapply(cc, table)
$abby
yes no
2 3
$billy
a b c d
1 1 2 1
See ?lapply as well. Note that a data frame is a list:
> is.list(cc)
[1] TRUE
> is.data.frame(cc)
[1] TRUE
> as.list(cc)
$abby
[1] no no yes yes no
Levels: yes no
$billy
[1] b c c d a
Levels: a b c d
HTH,
Marc Schwartz
On Wed, 2007-02-21 at 17:15 +0100, ONKELINX, Thierry wrote:
> John,
>
> Two things. You don't need to pout the cc variable in the apply. Use
> instead something like this.
>
> apply(cc, 2, fn1, y = mylist)
>
> But this still doesn't solve your problem. You'll need to rewrite your
> function like this.
>
> > fn2 <- function(x, y, i){
> + tt <- table(x[, i])
> + names(tt) <- y[[i]]
> + return(tt)
> + }
> > sapply(1:ncol(cc), fn2, x = cc, y = mylist)
> [[1]]
> yes no
> 2 3
>
> [[2]]
> a b c d
> 1 1 2 1
>
> Cheers,
>
> Thierry
> -----Oorspronkelijk bericht-----
> Van: r-help-bounces at stat.math.ethz.ch
> [mailto:r-help-bounces at stat.math.ethz.ch] Namens John Kane
> Verzonden: woensdag 21 februari 2007 16:47
> Aan: R R-help
> Onderwerp: [R] Trying to get an apply to work with a list in applying
> names totables
>
> I am trying to use apply and a list to supply names
> to a set of tables I want to generate. Below is an
> example that I hope mimics the larger original
> problem.
>
> EXAMPLE
>
> aa <- c( 2,2,1,1,2)
> bb <- c(5,6,6,7,4)
> aan <- c("yes", "no")
> bbn <- c("a", "b", "c", "d")
> mynames <- c("abby", "billy")
> mylist <- list(aan, bbn); names(mylist) <- mynames
>
> cc <- data.frame(aa,bb)
> fn1 <- function(x,y) {tt <- table(x); names(tt)<-
> mylist[[y]]}
> jj <-apply(cc, 2, fn1(cc,mylist))
>
> RESULT:
> Error in fn1(cc, mylist) : invalid subscript type
>
> To be honest I didn't expect it to work since that
> fin1(cc looks recursive but oh well...
>
> Can anyone offer a solution or some advice here. It
> would be greatly appreciated
More information about the R-help
mailing list