Passing function argument to formula

前端 未结 2 579
北荒
北荒 2021-01-16 05:24

I\'m trying to understand why

foo = function(d,y,x) {
    fit = with(d, lm(y ~ x))
}
foo(myData, Y, X)

won\'t work, where for instance

2条回答
  •  时光说笑
    2021-01-16 06:13

    Y and X are your column names, not variables. They wouldn't in this case, be arguments to your function unless you passed them in as strings and essentially call

    lm(mydata[,"Y"]~ mydata[,"X"])
    

    If you were to run ls() on your console, Y and X would most likely not be there, so the function won't work. Print both x and y prior to the fit = call, and you'll likely see NULLs, which won't fly in lm.

    One way to do this in your form is the following

    lmwrap<-function(df, yname, xname){
    fit=lm(d[,yname] ~ d[,xname])
    }
    
    lmwrap(mydata,"Y", "X")
    

    But you could just make the lm call like regular

提交回复
热议问题