Re: [S] Question - Coding numeric vectors

Christian Keller (ckeller@aicos.com)
Wed, 25 Mar 1998 16:41:11 +0100


Scherer, Peter wrote:
>> ... 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.
>> ...

You may use sample() to generate multinomial random numbers
in the following way:

codes <- 1:5 # assume the feeding sites are coded as 1,2,3,4,5
probs <- c(.25, .35, .4, 0, 0) # the probabilities for codes
sample(codes, replace=T, size=20, prob=probs)

>> 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 ?

Although the above seems appropriate for your problem, here
is another solution which you may use in other situations.

probs <- c(.25, .35, .4, 0, 0)
cumprobs <- cumsum(probs)
x <- runif(20)
x
[1] 0.61622475 0.70762942 0.47158901 0.26379934 0.08361898 0.18712453
[7] 0.67306679 0.90311028 0.44146293 0.26535696 0.79952180 0.90691403
[13] 0.35247623 0.54702667 0.58091383 0.19503488 0.68323089 0.82288164
[19] 0.78709463 0.68989758

cut(x, breaks=c(0,cumprobs), include.lowest=T)
[1] 3 3 2 2 1 1 3 3 2 2 3 3 2 2 2 1 3 3 3 3
attr(, "levels"):
[1] "0.00+ thru 0.25" "0.25+ thru 0.60" "0.60+ thru 1.00"
[4] "1.00+ thru 1.00" "1.00+ thru 1.00"

>> 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.

You don't have to apologize for questions, not even for simple ones.

-- Christian

----------------------------------------------------------
Christian Keller Tel: +41 61 686 98 81
AICOS Technologies AG Fax: +41 61 686 98 88
Efringerstrasse 32 email: ckeller@aicos.com
CH-4057 Basel, Switzerland Web: http://www.aicos.com/
----------------------------------------------------------
-----------------------------------------------------------------------
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