Question

I have a question regarding loop in R.

For example, currently at t=0, there are 100 people alive. Basically, each person will be alive with a probability of exponential (-mu) in which i put the mu=0.1.

I want to generate 10 samples to get the number of people alive at t=1. So i have done and get the following.

command:

set.seed(123)
alive <- 100    
mu <- 0.1
sample <- 10
alive1 <- rbinom(sample,alive,exp(-mu)) 
alive1 

# [1] 92 88 91 87 86 95 90 87 90 91

and now, i want to keep continuing doing it until time t=20.

command :

alive2 <- rbinom(10,alive1,exp(-mu))
alive2
alive3 <- rbinom(10,alive2,exp(-mu))
alive3
....

alive20 <-rbinom (10,alive19,exp(-mu))
alive20

output :

alive2 <- rbinom(10,alive1,exp(-mu))
alive2

# [1] 78 80 81 78 81 82 83 83 83 77

alive3 <- rbinom(10,alive2,exp(-mu))
alive3

# [1] 67 71 72 63 72 73 75 75 77 72

...

however, i do not want to keep on repeating the command especially if i want to extend my time to a longer period. how do i do the looping in r for my problem?

thanks!

Was it helpful?

Solution

set.seed(123)
alive <- vector("list", 20)
mu <- 0.1
n <- 10

alive[[1]] <- rbinom(n, 100, exp(-mu))
for(i in 2:20)
    alive[[i]] <- rbinom(n, alive[[i-1]], exp(-mu))

I renamed the variable sample to n to avoid confusion with the commonly used function sample().

OTHER TIPS

set.seed(123)
alive <- 100    
mu <- 0.1
sample <- 10
alive1 <- rbinom(sample,alive,exp(-mu)) 


for ( i in 2:20)
{
    assign(
        paste0("alive",i),
        rbinom(10,get(paste0("alive",(i-1))),exp(-mu))
    )
}

Or @Backlin's suggestion of putting it in a list -

set.seed(123)
alive <- 100    
mu <- 0.1
sample <- 10
Aliveset <- vector(mode = "list", length = 20)
Aliveset[[1]] <- rbinom(sample,alive,exp(-mu)) 
for ( i in 2:20)
{
Aliveset[[i]] <- rbinom(10,Aliveset[[i-1]],exp(-mu))
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top