Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User defined functions as formula input

Tags:

r

Built-in functions in R can be used in formula objects, for example

reg1 = lm(y ~ log(x), data = data1)

How can I write my functions such that they can be used in formula objects?

fnMyFun = function(x) {
  return(x^2)
}
reg2  = lm(y ~ fnMyFun(x), data = data1)
like image 817
tchakravarty Avatar asked Sep 14 '26 01:09

tchakravarty


1 Answers

What you've got certainly works. One problem is that different modelling functions handle formulas in different ways. I think that as long as you return something that model.matrix can make sense of, you'll be fine. That would mean

  1. The function is vectorised; ie given a vector of length N, it returns a result also of length N

  2. It has to return an atomic vector or matrix (but not a list, or of type raw)

like image 78
Hong Ooi Avatar answered Sep 15 '26 17:09

Hong Ooi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!