[英]Pass function arguments that are variable names into formulae in R functions?
我正在尋找一種簡單的方法,將變量名稱的函數參數傳遞到R函數的公式中。
測試數據集:
set.seed(4892)
df.pass <- data.frame("alfa"=sample(1:9, 100, replace=T), "beta"=sample(1:9, 100, replace=T),
"theta"=sample(1:9, 100, replace=T), "out"=runif(100, 0, 1))
要進行功能的示例分析(測試交互模型是否不同):
lrtest(glm(out~alfa*beta, family = binomial("logit"), df.pass),
glm(out~alfa + beta, family = binomial("logit"), df.pass))
如果目標是創建通用函數invinteract
來解決上述問題,並使用任意變量名和數據集,那么將變量名從function()
參數傳遞到與out
, alfa
和beta
?
將原始變量名稱插入公式中不起作用,因為R試圖將名稱作為對象求值,但一無所獲。
將字符串變量名稱直接插入公式中也不起作用。
是否需要使用paste()
重構公式,還是有更直接的方法?
glm
還接受字符串而不是公式。 因此,您可以執行以下操作:
mytest <- function(DF, y, x1, x2) {
lrtest(glm(sprintf("%s ~ %s * %s", y, x1, x2), family = binomial("logit"), DF),
glm(sprintf("%s ~ %s + %s", y, x1, x2), family = binomial("logit"), DF))
}
mytest(df.pass, "out", "alfa", "beta")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.