如何使用调查包的 svyby 功能在多列上进行循环?

Ped*_*ani 5 loops r survey

我一直在尝试很多方法,但我没有解决问题。我找到了here、here和here,但我无法使它们适应我的问题。

我想传递两个字符串向量的组合,其中 'pop' 的每个元素将与 'territ' 的每个元素组合在一起,并通过数字向量(“enroll_lines”)覆盖“enroll”列的子集。因此,我想要在 svyby 函数内部进行三次迭代:在字符串向量中进行两次迭代,在子集数值向量中进行一次迭代。

我想要一个数据框,其中包含设计对象“dclus1”上三个向量的所有结果组合。

预先感谢您的关注和努力。

df <- apiclus1
df$pais <- 0
df$pop_tot <- 1

pop <- c("pop_tot", "stype", "awards")
territ <- c("pais","cname", "dname")
enroll_lines = c(355, 455, 555)

dclus1<-svydesign(id=~dnum, weights=~pw, data=df, fpc=~fpc)

svyloop <- function(vv1, vv2, dsgn, xx) {
  svyby( as.formula( paste0( "~" , vv1)) , by = as.formula( paste0( "~" , vv2)) , subset(dsgn, enroll < xx), svytotal , vartype = 'cv')
}
svyloop(pop, territ, dclus1, enroll_lines)
#Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) :  contrasts can be applied only to factors with 2 or more levels

sapply(dclus1, svyloop, pop, territ, enroll_lines)
#Even though keeping just columns with two or more leves, the column "enroll" is not found, as the message below returns:
#Error in subset.default(dsgn, enroll < xx) : object 'enroll' not found

**The other way I've tried was to put an "i" of iteration in the function.**
jj <- 1:3
svyloop <- function(vv1, vv2,, xx, i) {
  svyby( as.formula( paste0( "~" , vv1[i])) , by = as.formula( paste0( "~" , vv2[i])) , subset(dclus1, enroll < xx[i]), svytotal , vartype = 'cv')
}
svyloop(pop, territ, enroll_lines, jj)
sapply(dclus1, svyloop, pop, territ, enroll_lines)
#Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) :  contrasts can be applied only to factors with 2 or more levels

Run Code Online (Sandbox Code Playgroud)

小智 1

中的第一个参数sapply已循环,您不想迭代您的设计dclus1,而是迭代pop,territ和enroll_lines。您的解决方案无法工作,因为您没有为您的svytable功能提供设计对象。您可以使用多个sapplys 并且您的函数可以工作。简单但不优雅的解决方案:

sapply(pop, 
       function(x) sapply(territ, 
                          function(y) sapply(enroll_lines, function(z) 
                  svyloop(x, y, dclus1, z),
                  simplify = F),
             simplify = F),
         simplify = F)
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以获得表格的嵌套列表,并可以按照您喜欢的任何方式组合它们。

可能还有更有效的解决方案,mapply但嵌套的 sapply 也可以工作。