Lothar the Quick
Lothar the Quick

Reputation: 89

Using variable to select covariates for glm

I am running a simulation of multiple experiments using random data to create glm models. In each individual experiment I need to select different covariates to build the glm. Is there a way to use variable names to specify which covariates to use in the formula? For example, for a data frame called data that will contain the heading y plus a set of other headings that changes with each iteration, something like:

data <- data.frame(x1 = c(1:100),x2 = c(2:101),x3 = c(3:102),x4 = c(4:103),x5 = c(5,104),y = c(6:105))

#Experiment #1:
covars = c(x1,x2,x4)
glm(y ~ sum(covars),data=data)

#Experiment #2:
covars = c(x1,x3,x4,x5)
glm(y ~ sum(covars),data=data)

#Experiment #3:
covars = c(x2,x4,x5)
glm(y ~ sum(covars),data=data)

#etc...

So far, I have tried using this approach with the sum & colnames functions but I get the following error: "invalid 'type' (character) of argument"

Thank you!

Upvotes: 0

Views: 448

Answers (1)

akrun
akrun

Reputation: 887741

We can use . to represent all the columns except the dependent column 'y'

glm(y ~ ., data = data)

Upvotes: 0

Related Questions