Home > Mobile >  how to generate population using loops in r
how to generate population using loops in r

Time:03-16

I want to generate a population of size 10 using for loops in r as follows (I know there should be easier way to do this without using loops such as

nPop <- 10
agent.list.2<- data.frame(id = 1:nPop, 
                     state = 'S', #susceptible 
                     mixing = runif(nPop,0,1))

but I was just wondering if I can still generate the same population with for loop.)

nPop <- 10
for (i in 1:nPop){
  agent <- data.frame(id = i, 
                       state = 'S',#susceptible
                       mixing = runif(1,0,1))
}
agent

When I run the code I only got 10th agent. Is there any way to do so using for loops?

CodePudding user response:

Using map for iteration from the purrr package:

library(tidyverse)

nPop <- 10

agent <- map_dfr(seq_len(nPop), .f = function(i) {
  data.frame(id = i, 
             state = 'S',#susceptible
             mixing = runif(1,0,1))
})

Result:

> agent
   id state    mixing
1   1     S 0.5492558
2   2     S 0.9568374
3   3     S 0.9218307
4   4     S 0.2628695
5   5     S 0.6476246
6   6     S 0.9417889
7   7     S 0.2746807
8   8     S 0.1136945
9   9     S 0.2457556
10 10     S 0.9292233

If you want to use a for-loop, you can do this:

library(dplyr)

agent <- data.frame()

nPop <- 10

for(i in seq_len(nPop)) {
  df <- data.frame(id = i, 
                      state = 'S',#susceptible
                      mixing = runif(1,0,1))
  
  agent <- bind_rows(agent, df)
}

CodePudding user response:

If your preference is to stay within the realm of base R and if you prefer for-loops you could also go for:

nPop <- 10

agent <- data.frame(matrix(ncol = 3, nrow = nPop))
colnames(agent) <-c("id", "state", "mixing")

for (i in 1:nPop){
  agent[i,] <- c(i, 'S', runif(1,0,1))
}
agent
  • Related