I would like to calculate Linear mixed-effect models via for loop where there is always hard-coded Y and random effect. The X variables (var.nam[i]
) are to be loop through. I wrote the code and it is working (as I believe), but I would also like to subset X variable (var.nam[i]
) depending on the X variable (var.nam[i]
) type (numeric, factor) where:
when X variable (var.nam[i]
) is numeric, exclude all observation equal to 0
when X variable (var.nam[i]
) is factor, do not subset X variable (var.nam[i]
)
A short sample of my code is here:
for(i in 1:length(var.nam)) {
formula[i] <- paste0("Y", "~", paste0(c(var.nam[i], c("Season"),
c("Sex"),
c("Age"),
c("BMI"),
c("(1|HID)")), collapse=" "))
model <- lmer(formula[i], data = subset(data, paste0(c(var.nam[i])) != 0))
# loop continues...
}
As it is written now, it will subset all X variables (var.nam[i]
) regardless of the type. Is there any workaround or different way to subset variable, that would work in this specific case?
CodePudding user response:
Checking if this solution works is a bit hard without data or the complete for loop. Based on your question you want to conditionally subset, adding a if else statement should make this possible:
for(i in 1:length(var.nam)) {
formula[i] <- paste0("Y", "~", paste0(c(var.nam[i], c("Season"),
c("Sex"),
c("Age"),
c("BMI"),
c("(1|HID)")), collapse=" "))
data1 <- if(mode(var.nam[i]) == "numeric") {subset(data, paste0(c(var.nam[i])) !=0)} else {data}
model <- lmer(formula[i], data = data1)
# loop continues...
}