NelsonGon
NelsonGon

Reputation: 13319

How to let R predict user input

Let's say I have this function that returns the coefficients of a linear model:

lmfun<-function(df,yname,xname){
  y<-deparse(substitute(yname))
  x<-deparse(substitute(xname))
  f<-as.formula(paste0(y,"~",x))
  lm.fit<-do.call("lm",list(data=quote(df),f))
  coef(lm.fit)
}

Now using this function on mtcars I can type:

lmfun(mtcars,yname=mpg,disp)

However, how do I get R to predict a user's input just like it happens in several packages? That is before I finish typing mpg, R has already made a suggestion.

Upvotes: 1

Views: 160

Answers (1)

Julius Vainora
Julius Vainora

Reputation: 48211

Perhaps you want match.arg. For instance:

lmfun <- function(df, yname, xname){
  y <- match.arg(deparse(substitute(yname)), names(df))
  x <- match.arg(deparse(substitute(xname)), names(df))
  f <- as.formula(paste0(y, "~", x))
  lm.fit <- do.call("lm", list(data = quote(df), f))
  coef(lm.fit)
}
lmfun(mtcars, yname = mp, dis)
# (Intercept)        disp 
# 29.59985476 -0.04121512 

Of course, it has to be possible to unambiguously match the names:

lmfun(mtcars, yname = mp, d)
# Error in match.arg(deparse(substitute(xname)), names(df)) : 
#   'arg' should be one of “mpg”, “cyl”, “disp”, “hp”, “drat”, “wt”, “qsec”,
# “vs”, “am”, “gear”, “carb”  

This time it didn't work as d could be disp or drat.

Upvotes: 2

Related Questions