Conditional expression for a variable present in the model

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

Example. If B exists in the linear model

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

I want to do something. I used the summary function earlier to refer to the R-square.

summary(model)$r.squared

Maybe I'm looking for something like this

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

or

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

But I can not find xxx. Please help =)

+3
source share
5 answers

Try the following:

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

Another way:

if ("B" %in% names(coef(model)))
+2
source

:

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

, term.labels. :

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)

terms :

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

, , "B" :

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

A (somewhat inelegant) possible solutions:

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

where \\bcorresponds to the word boundary, and Bis the name of the variable you are looking for.

0
source

Source: https://habr.com/ru/post/1780006/


All Articles