Explore Courses Blog Tutorials Interview Questions
0 votes
in R Programming by (7.3k points)

Suppose I have a response variable and a data containing three covariates (as a toy example):

y = c(1,4,6)

d = data.frame(x1 = c(4,-1,3), x2 = c(3,9,8), x3 = c(4,-4,-2))

I want to fit a linear regression to the data:

fit = lm(y ~ d$x1 + d$x2 + d$y2)

Is there a way to write the formula, so that I don't have to write out each individual covariate? For example, something like

fit = lm(y ~ d)

(I want each variable in the data frame to be a covariate.) I'm asking because I actually have 50 variables in my data frame, so I want to avoid writing out x1 + x2 + x3 + etc.

1 Answer

0 votes

To include multiple variables from a data frame in a linear model, you can use the (.) identifier which means to include all the variables.

For example:

y <- c(1,3,6)

df <- data.frame(y = y, x1 = c(4,-1,3), x2 = c(3,9,8), x3 = c(4,-4,-2))

mod <- lm(y ~ ., data = df)

. means to include all variables not mentioned in the formula

For example:

Here. means to include x3 in the formula as x1 and x2 are already included.

lm(y ~ x1 + x2 + ., data = df)

Browse Categories