Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with formula objects in R

Tags:

r

I am trying to learn how to make my own functions with formula objects. I am mostly confused with how to parse them.

Lets say I have the following

gigl <- function(formula, data, family = gaussian()) 

Using the R dataset BOD

> BOD
  Time demand
1    1    8.3
2    2   10.3
3    3   19.0
4    4   16.0
5    5   15.6
6    7   19.8

It is easy to fit a linear model with lm

>lm(Time~demand, data=BOD)
Call:
lm(formula = Time ~ demand)

Coefficients:
(Intercept)       demand  
    -1.8905       0.3746

How can I make my own function by parsing a formula?

For example if I had

>gigl(Time~demand, data=BOD)

How can I parse the components? I don't really care what the function gigl does. I just want to know how to work with the formula.

Edit

Due to questions about a concrete example lets try the following:

Say that I want to use the inputs from a formula to build a cor() matrix. So from the above I would see the result of cor(Time,demand) and if more variables were added I would see the complete cor() of all inputs.

like image 752
Alex Avatar asked Feb 14 '18 21:02

Alex


1 Answers

Here's a function that takes a formula and transforms it into a call to the cor() function, then evaluates that call in an environment consisting of the data ...

f <- function(form,data) {
    form[[1]] <- quote(cor)
    eval(form,data)
}
f(demand~Time,BOD)
## [1] 0.8030693
like image 124
Ben Bolker Avatar answered Oct 04 '22 20:10

Ben Bolker