[R] calling svydesign function that uses model.frame

Thomas Lumley tlumley at u.washington.edu
Tue Apr 12 16:27:39 CEST 2005


On Mon, 11 Apr 2005, Richard Valliant wrote:

> I need help on calling the svydesign function in the survey package
> (although this error appears not to be specific to svydesign). I am
> passing parameters incorrectly but am not sure how to correct the
> problem.
>
> ## Call the main function PS.sim (one of mine).  The dots are
> parameters I omitted to simplify the question.
> ## y.col, str.col, clus.id, and PS.col are names of columns in the
> object pop.
>
> PS.sim(pop=small, y.col="NOTCOV",
> 		...,str.col="new.str", clus.id="new.psu",
> 		PS.col="PS.var", ...)
>
> ## A data.frame called sam.dat is generated by PS.sim.  Its first 3
> lines are:
>
> ID new.str PS.var new.psu NOTCOV       wts
> 213       1      3            2                 2          37.7
> 236       1      3            2                 2          37.7
> 286       1      2            2                 2          37.7

<snip>

> I need to call svydesign with the parms I use to invoke the main
> function PS.sim, i.e., ~clus.id and ~str.col.
> How do I do that?

Two possibilities
1/ construct a formula with as.formula and paste
svydesign(id=as.formula(paste("~",new.psu)), strata=as.formula(paste("~",str.col)),...)

For a working example
> data(api)
> psu<-"dnum"
> svydesign(id=as.formula(paste("~",psu)), weight=~pw,data=apiclus1)
1 - level Cluster Sampling design
With (15) clusters.
svydesign(id = as.formula(paste("~", psu)), weight = ~pw, data = apiclus1)

2/ use substitute()
A working example:
> psu<-"dnum"
> eval(substitute(svydesign(id=~id,weight=~pw, data=apiclus1),
                   list(id=as.name(psu))))
1 - level Cluster Sampling design
With (15) clusters.
svydesign(id = ~dnum, weight = ~pw, data = apiclus1)


As you can see, the second option is probably more cumbersome but has the 
advantage of producing a prettier-looking call.

 	-thomas




More information about the R-help mailing list