Save every R for loop iteration in a new list

I am using the dataprep function of the Synth package (see https://cran.r-project.org/web/packages/Synth/Synth.pdf).

I have the following command in R that I want to loop:

dataprep.out <- dataprep(foo=expenditures,
     predictors=c("pop_tot", "share_yng", "share_old", "unempl", "sign_pop_initiative", "cab_size", "parl_size"),
     predictors.op="mean",
     dependent="exp_welf",
     unit.variable="canton",
     unit.names.variable="canton_abr",
     time.variable="year",
     treatment.identifier=7,
     controls.identifier=c(6, 8, 15, 16),
     time.optimize.ssr=1980:1995,
     time.plot=1980:2007,
     time.predictors.prior=1980:1995
     )

class(dataprep.out)
[1] "list"

So far so good. The result is a list[8]. Now I want to loop the command (note the changes in treatment.identifier and controls.identifier:

for (i in c(6,8,15,16)){dataprep(foo=expenditures,
                     predictors=c("pop_tot", "share_yng", "share_old", "unempl", "sign_pop_initiative", "cab_size", "parl_size"),
                     predictors.op="mean",
                     dependent="exp_welf",
                     unit.variable="canton",
                     unit.names.variable="canton_abr",
                     time.variable="year",
                     treatment.identifier=i,
                     controls.identifier=c(6,8,15,16)[c(6,8,15,16) !=i],
                     time.optimize.ssr=1980:1995,
                     time.plot=1980:2007,
                     time.predictors.prior=1980:1995)}

How do I save every iteration in it’s own list? I’d like to have a list, e.g. dataprep.out”i”, for every iteration and therefore every object “i” (dataprep.out6; dataprep.out8 etc.).

I guess I have to create those objects first so the loop can save its results into the corresponding list. Nevertheless I am struggling with what object I have to create exactly. And I dont’ know how to tell the for loop to assign every result to a list that is varying only in “i” (dataprep.out”i”, where “i” is varying).

Answer

You can create list before and then add item to it like

i_list=c(6,8,15,16)
result_list=list()
for (i in seq(i_list)){
  result_list[[i]]=dataprep(...)}

But your need to changes in identifier

treatment.identifier=i_list[[i]],
controls.identifier=c(6,8,15,16)[c(6,8,15,16) !=i_list[[i]]]

But lapply variant as @zx8754 told better

result_list=lapply(i_list,function(i) dataprep(...))

Leave a Reply

Your email address will not be published. Required fields are marked *