Using svyglm within plyr call

2019-04-10 10:21发布

问题:

This is clearly something idiosyncratic to R's survey package. I'm trying to use llply from the plyr package to make a list of svyglm models. Here's an example:

library(survey)
library(plyr)

foo <- data.frame(y1 = rbinom(50, size = 1, prob=.25),
                  y2 = rbinom(50, size = 1, prob=.5),
                  y3 = rbinom(50, size = 1, prob=.75),
                  x1 = rnorm(50, 0, 2),
                  x2 = rnorm(50, 0, 2),
                  x3 = rnorm(50, 0, 2),
                  weights = runif(50, .5, 1.5))

My list of dependent variables' column numbers

dvnum <- 1:3

Indicating no clusters or strata in this sample

wd <- svydesign(ids= ~0, strata= NULL, weights= ~weights, data = foo)

A single svyglm call works

svyglm(y1 ~ x1 + x2 + x3, design= wd)

And llply will make a list of base R glm models

llply(dvnum, function(i) glm(foo[,i] ~ x1 + x2 + x3, data = foo))

But llply throws the following error when I try to adapt this method to svyglm

llply(dvnum, function(i) svyglm(foo[,i] ~ x1 + x2 + x3, design= wd))

Error in svyglm.survey.design(foo[, i] ~ x1 + x2 + x3, design = wd) : 
all variables must be in design= argument

So my question is: how do I use llply and svyglm?

回答1:

DWin was on to something with his comment about correct formula.

reformulate will do this.

dvnum <- names(foo)[1:3]

llply(dvnum, function(i) {
    svyglm(reformulate(c('x1', 'x2', 'x3'),response = i), design = wd)})


标签: r plyr