Mistake with svychisq - "contrast can be applied to factors with 2 or more levels"

Error in contrasts<-( *tmp*, value = contr.funs [1 + isOF [nn]]): contrasts can only be applied to factors with 2 or more levels

I get this error whenever I try to use the svychisq function in the poll package. However, the function works when I use the svytable function. The error indicates a coefficient with 2 or more levels - the DIED variable is a factor with 2 levels, 0 and 1.

> svytable(~COHORT+DIED, design=df_srvy)

  DIED
COHORT         0         1
  1997 26726.584  1647.118
  2000 26958.912  1628.692
  2003 30248.533  1599.094
  2006 36602.173  1586.526
  2009 44004.732  2531.597
  2012 56037.874  2766.386

> svychisq(~COHORT+DIED, design=df_srvy)
Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) : 
contrasts can be applied only to factors with 2 or more levels

EDIT:

Here is a small example of a subset of the problem

sample <- structure(list(DISCWT = c(1.36973, 1.4144, 1.41222, 1.41222, 
1.4144, 1.4144, 1.41222, 1.41222, 1.4144, 1.41222, 1.41222, 1.41222, 
1.41222, 1.4144, 1.4144), COHORT = c(1997L, 2012L, 2000L, 2003L, 
2006L, 2006L, 2009L, 2012L, 2012L, 1997L, 2003L, 2006L, 2006L, 
2003L, 1997L), DIED = c(1L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 1L, 
0L, 0L, 0L, 0L, 1L)), row.names = c(NA, -15L), class = c("tbl_df", 
"tbl", "data.frame"), .Names = c("DISCWT", "COHORT", "DIED"))

sample_survey <- sample %>% as_survey_design(., weight = DISCWT)

svychisq(~DIED+COHORT, sample_survey)
+4
source share
1 answer

thanks for the minimal reproducible example

library(srvyr)
library(survey)

sample <- structure(list(DISCWT = c(1.36973, 1.4144, 1.41222, 1.41222, 
1.4144, 1.4144, 1.41222, 1.41222, 1.4144, 1.41222, 1.41222, 1.41222, 
1.41222, 1.4144, 1.4144), COHORT = c(1997L, 2012L, 2000L, 2003L, 
2006L, 2006L, 2009L, 2012L, 2012L, 1997L, 2003L, 2006L, 2006L, 
2003L, 1997L), DIED = c(1L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 1L, 
0L, 0L, 0L, 0L, 1L)), row.names = c(NA, -15L), class = c("tbl_df", 
"tbl", "data.frame"), .Names = c("DISCWT", "COHORT", "DIED"))


# error because svychisq dies on tibble types
sample_survey <- sample %>% as_survey_design(., weight = DISCWT)
svychisq(~COHORT+DIED, sample_survey)

# probably somewhere around here in lumley code
# rowvar <- unique(design$variables[, as.character(rows)])
# colvar <- unique(design$variables[, as.character(cols)])



# works fine
x <- sample
x <- data.frame(x)
sample_survey <- svydesign( ~ 1 , data = x , weight = ~ DISCWT )
svychisq(~COHORT+DIED, sample_survey)
+6
source

Source: https://habr.com/ru/post/1655358/


All Articles