Thev
Thev

Reputation: 1125

R - how to simulate random variable?

I'm okay with a regular distribution, say simulating a fair die.

But what if I wanted to simulate the following:

X_n = 2 (with probability 0.6) or -1 (with probability 0.4) when n is odd.

X_n = -2 (with probability 0.6) or 1 (with probability 0.4) when n is even.

Any advice?

Upvotes: 1

Views: 938

Answers (2)

Terru_theTerror
Terru_theTerror

Reputation: 5017

Try this:

sample(c(2,-1), size=100, replace=TRUE, prob=c(0.6,0.4))
sample(c(-2,1), size=100, replace=TRUE, prob=c(0.6,0.4))> n<-20

An example on the first 20 numbers:

n<-20
odd_n<-seq(1,n,by=2)
even_n<-seq(2,n,by=2)

odd<-sample(c(2,-1), size=n/2, replace=TRUE, prob=c(0.6,0.4))
even<-sample(c(-2,1), size=n/2, replace=TRUE, prob=c(0.6,0.4))

db<-data.frame(value=c(odd,even),number=c(odd_n,even_n))

row.names(db) <- NULL
db
   value number
1     -1      1
2     -2      2
3      2      3
4     -2      4
5      2      5
6     -2      6
7     -1      7
8      1      8
9      2      9
10    -2     10
11     2     11
12     1     12
13     2     13
14    -2     14
15    -1     15
16    -2     16
17    -1     17
18     1     18
19     2     19
20     1     20

Upvotes: 5

chinsoon12
chinsoon12

Reputation: 25223

You can use runif to generate samples and threshold it at 0.4 to decide whether it should be -1/1 or 2/-2 depending on whether n is odd or even.

sim <- function(n) {
    x <- runif(n)
    if (n %% 2 == 0) {
        ret <- ifelse(x < 0.4, 1, -2)
    } else {
        ret <- ifelse(x < 0.4, -1, 2)
    }
    return(ret)
}

to verify distribution

hist(sim(10000))
hist(sim(10001))

Upvotes: 2

Related Questions