[R] Apply or Tapply to Build Set of Tables

Kenn Konstabel lebatsnok at gmail.com
Tue May 24 12:00:50 CEST 2011


On Tue, May 24, 2011 at 4:01 AM, Jim Holtman <jholtman at gmail.com> wrote:
> untested
>
> x <- lapply(names(infert),function(a)table(infert[[a]]))

This part can be simpler:

lapply(infert,table)

But extending it to the rest of the problem (i.e., 2-way tables) is
not trivial and can be confusing.

# 1
lapply(infert, function(a) mapply(chisq.test, x=infert,
MoreArgs=list(y=a), SIMPLIFY=FALSE))

# 2
combn(names(infert), 2, function(x) chisq.test(infert[[x[1] ]],
infert[[x[2] ]]), simplify=FALSE)


Many people would prefer a loop instead.


>
> extend this to the rest of your problem.
>
> Sent from my iPad
>
> On May 23, 2011, at 20:33, "Sparks, John James" <jspark4 at uic.edu> wrote:
>
>> Dear R Helpers,
>>
>> First, I apologize for asking for help on the first of my topics.  I have
>> been looking at the posts and pages for apply, tapply etc, and I know that
>> the solution to this must be ridiculously easy, but I just can't seem to
>> get my brain around it.  If I want to produce a set of tables for all the
>> variables in my data, how can I do that without having to type them into
>> the table command one by one.  So, I would like to use (t? s? r?)apply to
>> use one command instead of the following set of table commands:
>>
>> data(infert, package = "datasets")
>> attach(infert)
>>
>> table.education<-table(education)
>> table.age<-table(age)
>> table.parity<-table(parity)
>> etc.
>>
>>
>> To make matters worse, what I subsequently need is the chi-square for each
>> and all of the pairs of variables.  Such as:
>>
>> chi.education.age<-chisq.test(table(education,age))
>> chi.education.parity<-chisq.test(table(education,parity))
>> chi.age.parity<-chisq.test(table(age,parity))
>> etc.
>>
>> Your guidance would be much appreciated.
>>
>> --John J. Sparks, Ph.D.
>>
>> ______________________________________________
>> R-help at r-project.org 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.
>
> ______________________________________________
> R-help at r-project.org 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