> > Hi all, > I have a vector xm say: xm = c(1,2,3,4,5,5,5,6,6) > > I want to return a vector with the corresponding probabilities based on the > amount of times the numbers occurred. For example, I should get the > following vector for xm: > prob.xm = c(1/9, 1/9, 1/9, 1/9, 3/9, 3/9, 3/9, 2/9, 2/9) >Using prop.table gives: Usage (with table)> prob.xm <- round( prop.table(table(xm)), digits=3) > prob.xmxm 1 2 3 4 5 6 0.111 0.111 0.111 0.111 0.333 0.222 But I want the entire length of probabilities, not just a condensed version. Any help is greatl appreciated. -- Thanks, Jim. [[alternative HTML version deleted]]
If the values in xm are always going to be consecutive integers 1:n, then this:> prob.xm[xm]xm 1 2 3 4 5 5 5 6 6 0.111 0.111 0.111 0.111 0.333 0.333 0.333 0.222 0.222 otherwise:> prob.xm[as.numeric(as.factor(xm))]xm 1 2 3 4 5 5 5 6 6 0.111 0.111 0.111 0.111 0.333 0.333 0.333 0.222 0.222 (equivalent in this case). Sarah On Thu, Sep 22, 2011 at 3:41 PM, Jim Silverton <jim.silverton at gmail.com> wrote:>> >> Hi all, >> I have a vector xm say: ?xm = c(1,2,3,4,5,5,5,6,6) >> >> I want to return a vector with the corresponding probabilities based on the >> amount of times the numbers occurred. For example, I should get the >> following vector for xm: >> prob.xm = c(1/9, 1/9, 1/9, 1/9, 3/9, 3/9, 3/9, 2/9, 2/9) >> > > Using prop.table gives: > > > Usage (with table) > >> prob.xm <- round( prop.table(table(xm)), digits=3) >> prob.xm > xm > ? 1 ? ? 2 ? ? 3 ? ? 4 ? ? 5 ? ? 6 > 0.111 0.111 0.111 0.111 0.333 0.222 > > But I want the entire length of probabilities, not just a condensed version. > Any help is greatl appreciated. > >-- Sarah Goslee http://www.functionaldiversity.org
Try this:
long.prop.table <- function(x) {
x <- as.factor(x)
p = tabulate(x)/length(x)
p[x]
}
Michael Weylandt
On Thu, Sep 22, 2011 at 3:41 PM, Jim Silverton
<jim.silverton@gmail.com>wrote:
> >
> > Hi all,
> > I have a vector xm say: xm = c(1,2,3,4,5,5,5,6,6)
> >
> > I want to return a vector with the corresponding probabilities based
on
> the
> > amount of times the numbers occurred. For example, I should get the
> > following vector for xm:
> > prob.xm = c(1/9, 1/9, 1/9, 1/9, 3/9, 3/9, 3/9, 2/9, 2/9)
> >
>
> Using prop.table gives:
>
>
> Usage (with table)
>
> > prob.xm <- round( prop.table(table(xm)), digits=3)
> > prob.xm
> xm
> 1 2 3 4 5 6
> 0.111 0.111 0.111 0.111 0.333 0.222
>
> But I want the entire length of probabilities, not just a condensed
> version.
> Any help is greatl appreciated.
>
>
>
> --
> Thanks,
> Jim.
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help@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]]