1

I wanted to use mselec function from drc package for selecting the best model of a dose-response dataset. However, mselect does not work if you use it inside a function.

The following code works:

library(drc)
ryegrass.m1 <- drm(rootl~conc, data = ryegrass, fct = LL.4())

mselect(ryegrass.m1,list(LL.5(), LN.4(), W1.4(), W2.4()))

But not this one:

best.fit=function(data){  
model1=drm(rootl~conc, data=data, fct=LL.4())
M1=drc::mselect(model1, list(LL.5(), LN.4(), W1.4(), W2.4()))
return(M1)
}

best.fit(ryegrass)

I think the problem is related with the environments in R, but I don't know how to fix it. Someone could help me please?

2 Answers2

0

I manage to solve the problem like this:

best.fit=function(data){
  mf <- match.call(expand.dots = FALSE)
  m <- match(c("data"), names(mf), 0L)
  data.name=as.character(mf[m])

  model1=eval(parse(text=paste0('drm(rootl~conc, data=',data.name, ',fct=LL.4())')))
  M1=drc::mselect(model1, list(LL.5(), LN.4(), W1.4(), W2.4()))
  return(M1)
}

best.fit(ryegrass)

There should be better ways to do it, but at least it works for me now.

0

It seems that the update function within mselect doesn't access the original dataframe when run from inside a function. My solution was to add a data argument at line 34.

[1]     my_mselect <- function(...
...
[33]    tempObj <- try(update(object, fct = fctList[[i]],
[34]                          data = object$origData),    # <--- line added here
[35]                          silent = TRUE)

I also noticed that the reference to the model variables doens't work either if their relative positions are used instead of their original names, for instance when using drm(data[, 1] ~ data[, 2], fct = LL.4()). To avoid this you can use a temporary dataframe in your function, set the variable names as you want, and use these names in the drm call.

best.fit <- function(data){
  tmp_data <- data
  names(tmp_data) <- c("Var1", "Var2")
  model1 <- drm(Var1 ~ Var2, data = tmp_data, fct = LL.4())
  M1 <- my_mselect(model1, list(LL.5(), LN.4(), W1.4(), W2.4()))
  return(M1)
}
Nelson
  • 1
  • 1