[R] how to select an element from a vector based on a probability

Rui Barradas ruipbarradas at sapo.pt
Thu Apr 10 20:55:39 CEST 2014


Hello,

Use ?sample.

sample(x, 1, prob = x)

Hope this helps,

Rui Barradas

Em 10-04-2014 19:49, Simone Gabbriellini escreveu:
> Hello List,
>
> I have an array like:
>
> c(4, 3, 5, 4, 2, 2, 2, 4, 2, 6, 6, 7, 5, 5, 5, 10, 10, 11, 10,
> 12, 10, 11, 9, 12, 10, 36, 35, 36, 36, 36, 35, 35, 36, 37, 35,
> 35, 38, 35, 38, 36, 37, 36, 36, 37, 36, 35, 35, 36, 36, 35, 35,
> 36, 35, 38, 35, 35, 35, 36, 35, 35, 35, 6, 5, 8, 6, 6, 7, 1,
> 7, 7, 8, 9, 7, 8, 7, 7, 13, 13, 13, 14, 13, 13, 13, 14, 14, 15,
> 15, 14, 13, 14, 39, 39, 39, 39, 39, 39, 41, 40, 39, 39, 39, 39,
> 40, 39, 39, 41, 41, 40, 39, 40, 41, 40, 41, 40, 40, 40, 39, 41,
> 39, 39, 39, 39, 40, 39, 39, 40, 40, 39, 39, 39, 1, 4, 3, 4)
>
> I would like to pick up an element with a probability proportional to
> the element value, thus higher values should be picked up more often
> than small values (i.e., picking up 38 should be more probable than
> picking up 3)
>
> Do you have any idea on how to code such a rich-get-richer mechanism?
>
> Best regards,
> Simone
>




More information about the R-help mailing list