[R] simple question with table()
Berwin A Turlach
berwin at maths.uwa.edu.au
Sun Nov 30 11:15:53 CET 2008
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
=========================== 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
More information about the R-help
mailing list