Skip to content
Prev 280252 / 398502 Next

Generating input population for microsimulation

Dear Jan,

Thanks for your reply.

The first solution works well for my needs for now, but I have a question about the second. If I run your code and then call the function:

generate_unit(10)

I get an error that

Error in unit$size : $ operator is invalid for atomic vectors


Did you experience the same thing?

In any case, I will definitely take a look at the plyr package, which I'm sure will be useful in the future.

Thanks again!

Emma



----- Original Message -----
From: Jan van der Laan <rhelp at eoos.dds.nl>
To: "r-help at r-project.org" <r-help at r-project.org>
Cc: Emma Thomas <thomas_ek at yahoo.com>
Sent: Wednesday, December 14, 2011 6:18 AM
Subject: Re: [R] Generating input population for microsimulation

Emma,

If, as you say, each unit is the same you can just repeat the units to obtain the required number of units. For example,


? unit_size <- 10
? n_units <- 10

? unit_id <- rep(1:n_units, each=unit_size)
? pid? ?  <- rep(1:unit_size, n_units)
? senior? <- ifelse(pid <= 2, 1, 0)

? pop <- data.frame(unit_id, pid, senior)


If you want more flexibility in generating the units, I would first generate the units (without the persons) and then generate the persons for each unit. In the example below I use the plyr package; you could probably also use lapply/sapply, or simply a loop over the units.

? library(plyr)

? generate_unit <- function(unit) {
? ? ? pid <- 1:unit$size
? ? ? senior <- rep(0, unit$size)
? ? ? senior[sample(unit$size, 2)] <- 1
? ? ? return(data.frame(unit_id=unit$id, pid=pid, senior=senior))
? }

? units <- data.frame(id=1:n_units, size=unit_size)

? library(plyr)
? ddply(units, .(id), generate_unit)


HTH,

Jan




Emma Thomas <thomas_ek at yahoo.com> schreef: