R:将参数传递给R函数中的glm [英] R : Pass argument to glm inside an R function
问题描述
我试图习惯R中的范围问题。我想在函数内部调用函数 glm()
,但它不起作用,显然对于范围的原因我没有设法解决功能 assign()
或 eval()
。
下面是一个简化版本:
ao < - function(y,x, phi = seq(0,1,0.1),数据集,权重){
logLikvector< - rep(0,length(phi))#以后要被替换的零向量
for(i in 1 :length(phi)){#循环使用glm()
fit< -gmm(y_x,data = dataset,family = binomial,weights = weights)
logLikvector [i]< - logLik(fit)#获得日志可能性
}
logLikvector
}
现在我想在我的数据集上使用函数ao()
$ p $ ao(y = Prop,x = Age, dataset = mydata,weights = Total)
这不行k,但以下工作:
ao(y = mydata $ Prop,x = mydata $年龄,数据集= mydata,权重= mydata $ Total)
有谁知道该怎么办?
任何帮助将不胜感激!
顺便说一句,这里是如何使用我正在使用的数据集复制我的问题
<$数据库(MASS)
数据(月经初潮)
mydata< - 初潮
mydata $ Prop< - mydata $菜单/ mydata $总计
替代解决方案(@DWin建议)。
函数(y,x,数据集,权重){
f < - 替代(glm(y_x,data = dataset,weights = weights, family = binomial))
logLik(eval(f))
}
I am trying to get used to scoping issues in R. I'd like to call the function glm()
inside a function but it does not work, apparently for scoping reasons I did not manage to fix with the functions assign()
or eval()
.
Here is a simplified version:
ao <- function (y, x, phi = seq (0,1,0.1), dataset, weights) {
logLikvector <- rep(0,length(phi)) # vector of zeros to be replaced thereafter
for (i in 1:length(phi)) { # loop to use glm()
fit <- glm (y ~ x, data = dataset, family = binomial, weights = weights)
logLikvector[i] <- logLik(fit) # get log likelihood
}
logLikvector
}
Now I want to use the function ao() on my dataset
ao (y = Prop, x = Age, dataset = mydata, weights = Total)
This does not work, but the following works:
ao (y = mydata$Prop, x = mydata$Age, dataset = mydata, weights = mydata$Total)
Does anyone know what to do ?
Any help would be greatly appreciated !!!
Btw, here is how to replicate my problem with the dataset I am using
library("MASS")
data(menarche)
mydata <- menarche
mydata$Prop <- mydata$Menarche / mydata$Total
Solution with substitute (@DWin suggestion).
function(y, x, dataset, weights){
f <- substitute(glm(y~x, data=dataset, weights=weights, family=binomial))
logLik(eval(f))
}
这篇关于R:将参数传递给R函数中的glm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!