# Re: [R] Sum(Random Numbers)=100

From: Kenn Konstabel <lebatsnok_at_gmail.com>
Date: Wed, 09 Jul 2008 00:11:05 +0300

On Tue, Jul 8, 2008 at 9:53 AM, Shubha Vishwanath Karanth < shubhak_at_ambaresearch.com> wrote:

> ...actually I need to allocate certain amount of money (here I mentioned
> it as 100) to a randomly selected stocks(50 stocks)... i.e., 100 being
> divided among 50 stocks and preferably all are integer allocations(i.e.,
> 5 8 56 12 etc without any decimals)...

so perhaps you can reformulate your problem: instead of generating random numbers with their sum constrained to be 100, it could be dividing 100 units randomly between 50 "bins", which is, essentially, random sampling with replacement

stocks <- 1:50
money <- 100
allocations <- sample(stocks, money, replace=TRUE) # here you can add a prob argument to sample() # especially if you expect the results to be something like " 5 8 56 12 etc "
allocations <- table(factor(allocations, levels=stocks)) # or, equivalently, colSums(outer(allocations, stocks, "=="))

I don't know if this solves your problem but at least it's guaranteed to sum to 100 and give you only integer values.

Kenn

[[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. Received on Tue 08 Jul 2008 - 21:19:19 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 Tue 08 Jul 2008 - 21:31:57 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.