Reputation: 245
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
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
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