How to let R predict user input

前端 未结 1 728
梦如初夏
梦如初夏 2021-01-16 03:53

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&l         


        
相关标签:
1条回答
  • 2021-01-16 04:39

    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.

    0 讨论(0)
提交回复
热议问题