0

I am trying to loop over my data table columns and apply glm to each column using a for loop.

for(n in 1:ncol(dt)){
  model = glm(y ~ dt[, n], family=binomial(link="logit"))
}

Why doesn't this work? I am getting this error:

Error in `[.data.table`(dt, , n) : 
  j (the 2nd argument inside [...]) is a single symbol but column name 'n' is not found. Perhaps you intended DT[, ..n]. This difference to data.frame is deliberate and explained in FAQ 1.1. 

I nearly managed to make it work using something like dt[[n]], but I think it gets rid of the column name.

0

2 Answers 2

3

Using lapply to iterate over columns and reformulate to construct the formula.

model_list <- lapply(names(dt), function(x) 
                     glm(reformulate(x, 'y'), dt, family=binomial(link="logit")))
Sign up to request clarification or add additional context in comments.

Comments

0

We can create a formula with paste and use that in glm

model <- vector('list', ncol(dt))
for(n in 1:ncol(dt)){
     model[[n]] = glm(as.formula(paste0('y ~ ',  names(dt)[n])),
               data = dt, family=binomial(link="logit"))
     }

2 Comments

This doesn't work for me. I get a ` Error in eval(predvars, data, env) : object 'y' not found `
@user572780 I guess this is the similar question you asked there. It works with as.formula

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.