Re: [R] simple question with table()

From: Berwin A Turlach <berwin_at_maths.uwa.edu.au>
Date: Sun, 30 Nov 2008 18:15:53 +0800

G'day Simone,

On Sun, 30 Nov 2008 11:05:13 +0100
Simone Gabbriellini <simone.gabbriellini_at_gmail.com> wrote:

> my problem should be easy to fix, but I couldn't find a solution by
> myself...
>
> In my survey, there is a question with 14 possible answers. None of
> the respondents choose the 13th answer, so when I table() the
> results, R says:
[...]
> 13 is missing... anyone knows how to tell table() that there are 14
> modalities in the answers?

The easiest way is probably to turn your data into a factor with the appropriate set of levels:

R> dat <- sample(c(1:12,14), 100, replace=TRUE) R> table(factor(dat, levels=min(dat):max(dat)))

 1 2 3 4 5 6 7 8 9 10 11 12 13 14  9 5 4 7 7 11 8 10 9 8 6 11 0 5

that was once the solution of one of my colleagues and I find it somewhat nicer than the one I came up with:

R> rng <- min(dat):max(dat)
R> res <- colSums(outer(dat, min(dat):max(dat), "=="))
R> names(res) <- rng
R> res

 1 2 3 4 5 6 7 8 9 10 11 12 13 14
 9 5 4 7 7 11 8 10 9 8 6 11 0 5  

HTH. Best wishes,

        Berwin


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. Received on Sun 30 Nov 2008 - 10:20:42 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sun 30 Nov 2008 - 11:30:28 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive