[R] Trying to get an apply to work with a list in applying names totables
John Kane
jrkrideau at yahoo.ca
Thu Feb 22 01:37:01 CET 2007
Thanks Thierry, it works perfectly. And your
explanation of what sapply was doing was really
helpful.
Actually, your solution is showing me that whoever
input the data didn't stick to the coding manual by
that' another story.
--- "ONKELINX, Thierry" <Thierry.ONKELINX at inbo.be>
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
>
------------------------------------------------------------------------
> ----
>
> ir. Thierry Onkelinx
>
> Instituut voor natuur- en bosonderzoek / Reseach
> Institute for Nature
> and Forest
>
> Cel biometrie, methodologie en kwaliteitszorg /
> Section biometrics,
> methodology and quality assurance
>
> Gaverstraat 4
>
> 9500 Geraardsbergen
>
> Belgium
>
> tel. + 32 54/436 185
>
> Thierry.Onkelinx at inbo.be
>
> www.inbo.be
>
>
>
> Do not put your faith in what statistics say until
> you have carefully
> considered what they do not say. ~William W. Watt
>
> A statistical analysis, properly conducted, is a
> delicate dissection of
> uncertainties, a surgery of suppositions.
> ~M.J.Moroney
>
> -----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
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained,
> reproducible code.
>
More information about the R-help
mailing list