# 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

> 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

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

• Full address ============================= Berwin A Turlach Tel.: +65 6516 4416 (secr) Dept of Statistics and Applied Probability +65 6516 6650 (self) Faculty of Science FAX : +65 6872 3919 National University of Singapore 6 Science Drive 2, Blk S16, Level 7 e-mail: statba_at_nus.edu.sg Singapore 117546 http://www.stat.nus.edu.sg/~statba

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.