在 R 中动态子集测量设计对象 [英] Subsetting Survey Design Objects Dynamically in R

查看:15
本文介绍了在 R 中动态子集测量设计对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何动态地对调查设计对象进行子集化.我已经构建了我的循环以发送字符串,并且不知道如何删除引号,因此 R 将其读取为调用.

I am trying to figure out how to subset a survey design objects dynamically. I have structured my loop to send in character strings, and don't know how to remove the quotes so R reads it as a call.

我想循环一些这样的(虽然这显然会中断,因为 SUBSET_VARIABLE %in% 4 需要是一个调用而不是一个字符串.:

I would like to loop through some like this (although this will obviously break because SUBSET_VARIABLE %in% 4 needs to be a call NOT a string. :

design <- svydesign( ~1 , weight = ~wt , data = mtcars ) 

for( SUBSET_VARIABLE in c("gear","carb") ){

    design <- subset( design ,  SUBSET_VARIABLE %in% 4 )

    a <- svymean(~mpg, design)

}

如果可能,我想避免在粘贴函数中定义语句,而不是使用 eval( parse ( text = statement ) ) ) 来执行它.另外,我想避免使用索引,因为我知道 survey.design 对象的子集方法执行其他任务(请参阅:getS3method("subset", "survey.design") ) 并希望确保动态运行子集与在循环外使用子集函数完全等效.感谢您提供的任何帮助

If possible I would like to avoid defining the statement in a paste function and than using eval( parse ( text = statement ) ) ) to execute it. Also, I would like to avoid using indexing, because I know that the subset method for survey.design objects performs other tasks (see: getS3method("subset", "survey.design") ) and want to ensure that running the subset dynamically is exactly equivalent to using the subset function out of a loop. Thanks for any help you can provide

马修

推荐答案

使用 evalquote - 我认为这应该可以让您获得所需的所有灵活性:

Use eval and quote - I think that should allow you all of the flexibility you want:

for( SUBSET_VARIABLE in c(quote(gear), quote(carb)) ){
    design <- subset( design ,  eval(SUBSET_VARIABLE) %in% 4 )

    a <- svymean(~mpg, design)
}

或者如果你想有字符串作为输入,你可以使用 get 代替:

Or if you want to have character strings as an input, you can use get instead:

for( SUBSET_VARIABLE in c("gear", "carb") ){
    design <- subset( design ,  get(SUBSET_VARIABLE) %in% 4 )

    a <- svymean(~mpg, design)
}

这篇关于在 R 中动态子集测量设计对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆