在R中的函数中插入变量名
我正在尝试构造一个函数,使用调查包计算一些方差。问题是我需要将变量的名称(而不是变量的值)插入到特定函数(svyby)中 是这样的:在R中的函数中插入变量名,r,survey,R,Survey,我正在尝试构造一个函数,使用调查包计算一些方差。问题是我需要将变量的名称(而不是变量的值)插入到特定函数(svyby)中 是这样的: myfun=function(variable) { svyby(~variable,~subpop,design,svymean) } myfun(P16) myfun = function(variable) { svyby(as.formula(paste("~", variable)), ~subpop, design, s
myfun=function(variable) {
svyby(~variable,~subpop,design,svymean)
}
myfun(P16)
myfun = function(variable) {
svyby(as.formula(paste("~", variable)),
~subpop, design, svymean)
}
这给了我错误。我也试过了
*base[,variable]*
而不是
*variable*
这里的问题是,base[,variable]
为我提供了变量值的向量,但我需要在设计对象中读取变量的名称。我的意思是,我需要函数像这样插入名称
svyby(~P16,~subpop,design,svymean)
我将感谢您的帮助,提前谢谢您,
冈萨罗看起来需要一个公式。您可以将
“~”
粘贴到字符串,并将用作.formula
,如下所示:
myfun=function(variable) {
svyby(~variable,~subpop,design,svymean)
}
myfun(P16)
myfun = function(variable) {
svyby(as.formula(paste("~", variable)),
~subpop, design, svymean)
}
然后调用如下:myfun(“P16”)
。请注意,您需要使用带引号的列名,因为您将其视为字符串
或者,您可以让函数采用以下公式:
myfun2 = function(formula) {
svyby(formula,
~subpop, design, svymean)
}
这样称呼它:
myfun2(~P16)
看起来它需要一个公式。您可以将“~”
粘贴到字符串,并将用作.formula
,如下所示:
myfun=function(variable) {
svyby(~variable,~subpop,design,svymean)
}
myfun(P16)
myfun = function(variable) {
svyby(as.formula(paste("~", variable)),
~subpop, design, svymean)
}
然后调用如下:myfun(“P16”)
。请注意,您需要使用带引号的列名,因为您将其视为字符串
或者,您可以让函数采用以下公式:
myfun2 = function(formula) {
svyby(formula,
~subpop, design, svymean)
}
这样称呼它:myfun2(~P16)