# [S] Question - Coding numeric vectors

Scherer, Peter (pscherer@dowagro.com)
Wed, 25 Mar 1998 07:54:49 -0500

I apologize for what may be a simple question, but a search of FAQ's,
V&R and the manuals have not given me a solution.

I am attempting to simulate termite behavior with regard to selection of
feeding sites. In setting up the simulation I need to generate what are
essentially multinomial random numbers to represent which feeding site
was chosen. Since I am unaware of a multinomial random number generator
in S-plus (please enlighten me if I have missed something here) I chose
to address the problem by defining a vector of probabilities
representing the likelihood that a single termite will feed at a given
site.

> probs <- c(.25, .35, .4, 0, 0) # Note the zero probabilities are required
for the simulation
# since two populations which may/may not overlap are being
simulated
> probs
[1] 0.25 0.35 0.40 0.00 0.00
>

> cumprobs <- cumsum(probs)
> cumprobs
[1] 0.25 0.60 1.00 1.00 1.00 # represents the cuts for the multinomial
distribution
# i.e. [ (0 - .25), (.25 - .6), (.6 - 1.0), 1, 1}

# these non-unique values seems to cause difficulty when using cut

I then define a random uniform vector and use this to represent which
feeding site the termite chose.
> runif(20)
[1] 0.21703925 0.72277879 0.74437123 0.38596214 0.12851351 0.51552633
[7] 0.64371102 0.56830148 0.60507390 0.05779583 0.60671867 0.93499253
[13] 0.65680210 0.42505073 0.29194357 0.08249836 0.47509364 0.30391841
[19] 0.85542345 0.27216188

Now to my real question. How do I take a numeric vector, such as
randvec <- runif(20), and code the values into which group the random
data falls as defined by cumprobs ? For the example random data I would
like the vector to be :

1 3 3 2 1 2 ...

Perhaps I am going the long way around the barn here, but the question
remains "How do I code a numeric vector with respect to the breaks or
groups given in another vector ?".

I have not included my attempts at coding this problem for two reasons
1) they may border on ridiculous and 2) I would prefer not to direct any
solutions down a particular thread based on my ignorance.

Any help given on this (which I'm sure is a simple) problem would be
most appreciated.

If this matters I am using Version 3.4 on SGI running IRIX 5.3.

Thanks to all,

Peter Scherer
Dow AgroSciences
-----------------------------------------------------------------------
This message was distributed by s-news@wubios.wustl.edu. To unsubscribe
send e-mail to s-news-request@wubios.wustl.edu with the BODY of the
message: unsubscribe s-news