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
Adding Arguments in R We can pass an argument to a function while calling the function by simply giving the value as an argument inside the parenthesis.
14.1 Functions in RFunctions can be passed as arguments to other functions. This is very handy for the various apply functions, like lapply() and sapply() . Functions can be nested, so that you can define a function inside of another function.
R passes everything by reference until you modify it. R creates a copy when you modify the object. You should always keep all the Object modifications in same function.
R functions can have many arguments (the default plot function has 16). Function definitions can allow arguments to take default values so that users do not need to provide values for every argument.
Solution with substitute (@DWin suggestion).
function(y, x, dataset, weights){
f <- substitute(glm(y~x, data=dataset, weights=weights, family=binomial))
logLik(eval(f))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With