我已经尝试了很多方法,但我无法解决问题。我发现here https://stackoverflow.com/questions/13402829/r-looping-through-in-survey-package, here https://stackoverflow.com/questions/16224306/subsetting-survey-design-objects-dynamically-in-r and here https://stackoverflow.com/questions/12573826/looping-through-dataset-variables-in-svy-package,但我无法使它们适应我的问题。
我想传递两个字符串向量的组合,其中“pop”的每个元素将与“territ”的每个元素组合,并通过数字向量(“enroll_lines”)覆盖“enroll”列的子集。因此,我想要在 svyby 函数内部进行三次迭代:在字符串向量上进行两次迭代,在子集数值向量内进行一次迭代。
我想要一个数据框,其中包含设计对象“dclus1”上三个向量的所有结果组合。
预先感谢您的关注和努力。
data(api)
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
我尝试过的另一种方法是在函数中放入迭代的“i”。
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)
#`对比tmp\`, value = contr.funs[1 + isOF[nn]]) :对比只能应用于具有 2 个或更多级别的因子