lamhine
lamhine

Reputation: 45

Error in creating complex survey design object with imputed data using mi and survey packages in R

EDIT: Duplicate of question answered here.

I am trying to work with survey weighted data where there is some substantial missingness across important variables. I am generally following the workflow from this archived tutorial on R-Forge. Unfortunately I am running into an error I can't seem to figure out when I attempt to reference the imputed data when create the complex survey design object.

I can't do a reproducible example of my actual data, but I run into the same issue when trying to do the same thing with the apiclus1 dataset included in the survey package, so putting that example below.

I removed several variables that are unimportant for imputation and a few that were causing issues - this should not meaningfully affect the example.

library(tidyverse)
library(survey)
library(mi)
library(mitools)

data(api)

apisub <- apiclus1 %>% select(-c("name", "sname", "dname", "cname", "flag", 
                                 "acs.46", "acs.core"))

mdf <- missing_data.frame(apisub)
mdf <- change(mdf, "cds", what = "type", to = "irrelevant")
mdf <- change(mdf, "stype", what = "type", to = "irrelevant")
mdf <- change(mdf, "snum", what = "type", to = "irrelevant")
mdf <- change(mdf, "dnum", what = "type", to = "irrelevant")
mdf <- change(mdf, "cnum", what = "type", to = "irrelevant")
mdf <- change(mdf, "fpc", what = "type", to = "irrelevant")
mdf <- change(mdf, "pw", what = "type", to = "irrelevant")

show(mdf)

imputations <- mi(mdf)

dsn1 <- svydesign(id = ~dnum, weights = ~pw, data = imputationList(imputations), fpc = ~fpc)

The error I get after running this last line says Error in as.list.default(X) : no method for coercing this S4 class to a vector.

Can someone help me understand what I'm doing wrong?

Upvotes: 0

Views: 205

Answers (1)

Anthony Damico
Anthony Damico

Reputation: 6114

not sure i can answer but maybe this helps a bit? it's not clear to me how the library(mi) is supposed to fill in the missing data? svydesign() expects a list of data.frame objects, so the library(tidyverse) and library(mi) might create types not supported by the survey library and mitools..

# is this how to extract the four imputed data.frames from the `imputations` object?
# i am not sure
w <- lapply( imputations@data , data.frame )

# four data.frame objects in a list will now work:
dsn1 <- svydesign(id = ~dnum, weights = ~pw, data = imputationList(w), fpc = ~fpc)

# still missings in this variable, is that expected?
MIcombine( with( dsn1 , svymean( ~ avg.ed ) ) )

# result, ignoring the missings
MIcombine( with( dsn1 , svymean( ~ avg.ed , na.rm = TRUE ) ) )

Upvotes: 0

Related Questions