rrandomsamplebernoulli-probability

Generating random value for number of people alive and how to transpose data in R


I have a question on generating a random sample. I am very new to R and have tried to do my own simulation but im not sure whether it is correct. Really hope someone can assist me.

For example, currently there are 100 people alive. Basically, each person either dies with probability 0.5 between now and next period or survive to next period with probability of 0.5 --> i.e Bernoulli trial with success probability of 0.5.

I want to generate 20 samples to get the number of people alive next year. So i have done the following.

#number of people alive at time k
alive <- 100   

#generate 20 samples to find number of people alive next period
alive1 <- rbinom(20,alive,0.5)    

#generating result from r
alive1  
[1] 75 70 69 70 73 65 69 73 72 77 73 68 69 72 71 70 70 62 73 73

Is it right?

And how to transpose my data in R? Currently my data is in row; looks like this:-

[1] 75 70 69 70 73 65 69 73 72 77 73 68 69 72 71 70 70 62 73 73

How do I change it to column, like this:

[1] 75    
[2] 70    
[3] 69    
....

[20] 73

Solution

  • Your code is correct, although the output you got is not correct, because the mean is way too far from 50 to have come from a binomial distribution. So I don't think that your alive1 was actually generated by the code you wrote. Here's a more typical sample:

    set.seed(123)
    alive<-100
    alive1<-rbinom(20,alive,0.5)
    alive1
    ##  [1] 49 50 46 61 44 54 48 54 59 46 54 54 49 55 52 50 48 47 56 46
    

    If you want it as a column vector (i.e. a matrix with one column), you can call as.matrix:

    alive1<-as.matrix(alive1)
    alive1
    ##       [,1]
    ##  [1,]   49
    ##  [2,]   50
    ##  [3,]   46
    ##  [4,]   61
    ##  [5,]   44
    ##  [6,]   54
    ##  [7,]   48
    ##  [8,]   54
    ##  [9,]   59
    ## [10,]   46
    ## [11,]   54
    ## [12,]   54
    ## [13,]   49
    ## [14,]   55
    ## [15,]   52
    ## [16,]   50
    ## [17,]   48
    ## [18,]   47
    ## [19,]   56
    ## [20,]   46