Marcus R
Marcus R

Reputation: 245

Conditional expression for if variable present in model

What I want to do is to make a condition for if there is a certain variable in linear model

Example. If there is a B in a linear model

model <- lm(Y ~ A + B + C)

I want to do something. I have used the summary function before to refer to R-squared.

summary(model)$r.squared

Probably I am looking for something like this

if (B %in% summary(model)$xxx)

or

if (B %in% summary(model)[xxx])

But I can't find xxx. Please help =)

Upvotes: 3

Views: 572

Answers (5)

Marek
Marek

Reputation: 50704

Yet another way:

if ("B" %in% variable.names(model)) ...

Upvotes: 2

nico
nico

Reputation: 51640

Another way:

if ("B" %in% names(coef(model)))

Upvotes: 2

G. Grothendieck
G. Grothendieck

Reputation: 269654

Try this:

if ("B" %in% all.vars(formula(model))) ...

Upvotes: 4

NPE
NPE

Reputation: 500367

A (somewhat inelegant) possible solutions would be:

length(grep("\\bB\\b",formula(model))) > 0

where \\b matches the word boundary and B is the variable name you're looking for.

Upvotes: 0

Gavin Simpson
Gavin Simpson

Reputation: 174813

One option is to grab the model terms from the fitted model and interrogate the term.labels attribute. Using some dummy data:

set.seed(1)
DF <- data.frame(Y = rnorm(100), A = rnorm(100), B = rnorm(100), C = rnorm(100))
model <- lm(Y ~ A + B + C, data = DF)

The terms object contains the labels in an attribute:

> attr(terms(model), "term.labels")
[1] "A" "B" "C"

So check if "B" is in that set of labels:

> if("B" %in% attr(terms(model), "term.labels")) {
+     summary(model)$r.squared
+ }
[1] 0.003134009

Upvotes: 1

Related Questions