Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R : Pass argument to glm inside an R function

Tags:

function

r

glm

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
like image 489
user1431694 Avatar asked Jun 01 '12 22:06

user1431694


People also ask

How do you pass data into a function in R?

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.

Can functions take another function as an argument in R?

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.

Does R pass reference?

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.

How many arguments can an R function have?

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.


1 Answers

Solution with substitute (@DWin suggestion).

function(y, x, dataset, weights){
  f <- substitute(glm(y~x, data=dataset, weights=weights, family=binomial))
  logLik(eval(f))
}
like image 156
Wojciech Sobala Avatar answered Sep 18 '22 20:09

Wojciech Sobala