Skip to content

Simulating categorical random variables in R

October 5, 2012

No base R solution with syntactic sugar. Plenty of suggestions. Here’s the ‘best’:

sample(letters[1:3], 1, replace = TRUE) # equal probability
sample(letters[1:3], 1, prob = c(.25, .25, .75), replace = TRUE) # unequal probability
sample(letters[1:3], 10, prob = c(.25, .25, .75), replace = TRUE) # iid sample

The unfortunate thing is that you have to specify the sample size as the second argument (or name it), unlike the standard rnorm, rbinom, etc. family of functions.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: