[R] Calculate the percentages of the "numbers" in every column.
Petr PIKAL
petr.pikal at precheza.cz
Wed Jan 13 12:02:39 CET 2010
Hi
r-help-bounces at r-project.org napsal dne 13.01.2010 01:36:31:
> tmp <- scan()
> 0 2 1 0 1 0 2 1 2 3 0 0 0 0 1 0 0 2 3 1
>
> dat <- matrix(tmp, byrow=T, ncol=4)
>
> apply(dat, 2, function(x, min.val, max.val) {
> tmp <- table(x)/length(x)
> res <- rep(0, max.val - min.val + 1)
> res[as.numeric(names(tmp)) - min.val + 1] <- tmp
> res
> }, 0, 3)
>
> Should do it (but I bet there is a more elegant way).
I am not sure if more elegant or efficient but
dat.m<-melt(as.data.frame(dat))
xtabs(~value+variable, dat.m)/nrow(dat)
gives you similar result
Regards
Petr
>
> Regards,
> Simon Knapp
>
> On Wed, Jan 13, 2010 at 5:25 AM, Kelvin <6kelvin6 at gmail.com> wrote:
>
> > Dear friends,
> >
> > I have a table like this, I have A B C D ... levels, the first column
> > you see is just the index, and there are different numbers in the
> > table.
> >
> > A B C D ...
> > 1 0 2 1 0
> > 2 1 0 2 1
> > 3 2 3 0 0
> > 4 0 0 1 0
> > 5 0 2 3 1
> > ...
> >
> > I want to calculate the frequencies or the percentages of the numbers
> > in every column.
> >
> > How do I get a table like this, the first column is the levels of
> > numbers, and the numbers inside the table are the percentages. All the
> > percentages should add up to 1 in every column.
> >
> > A B C D ...
> > 0 0.2 0.3 0.1 0.1
> > 1 0.1 0.1 0.2 0.1
> > 2 0.1 0.2 0.2 0.2
> > 3 0.2 0.1 0.1 0
> > ...
> >
> > Thanks your help!
> >
> > Kelvin
> >
> > ______________________________________________
> > 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.
> >
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> 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