简体   繁体   中英

Error while trying to use lapply for logistic regression in r

I created a subset of variable for the data (while still maintaining the rest of the data). Then I tried to use lapply to estimate many logistic regression models at the same time- looping through the subset as different predictor variables.

#Creating a list for the loop to run through
metab.start <- which(colnames(df) == "Anhydro_1.5_D_glucitolArea"); metab.start
metab.stop <- which(colnames(df) == "ErythritolArea"); metab.stop
metabolite.names <- colnames(df)[metab.start:metab.stop]

#logistic regression loop
mdls<-lapply(metabolite.names, function(X) glm(hpresponse1~X, data=df, 
family="binomial"))

But it produces this error:

Error in model.frame.default(formula = hpresponse1 ~ X, data = df, 
drop.unused.levels = TRUE) : 
variable lengths differ (found for 'X')

I am not sure, but I think the issue is the datatype for the subset object. When I used str() on the subset object (metabolite.names), it says it is a character. But I think lapply is for lists? Then there is also sapply and mapply you can use for vectors and matrices, correct? The other concern was that I don't think the individual data values were retained when that subset was made. Leading the error that the variable lengths are not the same? Do I need to subset a different way to create a matrix? Then use mapply? Can I do that and retain the variable names and observations both? Or is there a way to loop through using the object I have made? Am I wrong about what is wrong? if so, what could be the issue?

As another note, there are over 100 predictor variables I am attempting to loop through. I plan to add other predictor variables that will not loop. But I am just trying to get the loop to work first.

In your function, X is the name of a column, not the values in the column. Try

glm(as.formula(paste0("hpresponse1~",X)), ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM