[R] Using svychisq inside user-defined function

Sabatier, Jennifer F. (CDC/OID/NCHHSTP) fvv9 at cdc.gov
Wed May 19 23:49:13 CEST 2010


Hi R-help,

Yes, this is my second request for assistance in a single day....

I am attempting to use svychisq() inside a function  I made.  The goal
of this function is to produce a table of summary statistics that I can
later output to EXCEL (simple frequencies and sample sizes from regular
crosstabulation on dataset "data" but the chi-square using survey
methods on "audit").

Here's my code (I can't supply data for you as I am not that
sophisticated and the real data is not cleared for public consumption -
I really apologize):


# create my svydesign object

audit <- svydesign(id~id, strata=~field, weights=~wt, data=data,
fpc=~AllocProportion)

# my function to create my table

mkMyCrossTable <- function(X, svyX, T) {

tbl <- crosstab(X, data$SEX, prop.c=TRUE)
tbl <- data.frame(cbind(tbl$t, tbl$prop.col))
tbl$var <- rownames(tbl)

chisq <- svychisq(~svyX + SEX, design=audit, statistic="adjWald",
round=4)
chisq <- data.frame(do.call("cbind", chisq)
chisq <- data.frame(chisq[,3])

Table <- data.frame(tbl$var,
                    paste(formatC(tbl$X0.1*100, format="f", digits=1),
"%", sep=""), 
         		  tbl$X0,
			  paste(formatC(tbl$X1.1*100, format="f",
digits=1), "%", sep=""),
			  tbl$X1,
			  chisq[1])
Table[2: length(Table[,1]), 6] <- NA
Table <- NAToUnkown(Table, unknown = " ")
Colnames(Table) <- c(T, "Male (%)", "Male (n)", "Female (%)", "Female
(n)", "p-value")
Table

}

con3 <- mkMyCrossTable(data$con, con, "Constituency")





The error occurs with the "chisq <- svychisq(~X+SEX, design=audit,
statistic="adjWald", round=4)" part of my function.  I did debug() to
double check.

I get the error:  "Error in '[.data.frame'(design$variables, ,
as.character(rows)) :
                     Undefined columns selected"

My suspicion is that it doesn't like me referencing the variables in
"audit", but I don't know how to fix it.


Thanks,

Jen

PS.  I know my table-making function is terribly inelegant...



More information about the R-help mailing list