Convincing R to exclude single level factors when using lm() in a for loop in some subsets (but not all)
<p>I am working on a large dataset with 19 subcohorts for which I want to run a lineair regression model to estimate BMI.</p>

<p>One of the covariates I am using is sex, but some subcohorts consist only of men, which causes problems in my loop. 
If I try to run a linear regression model, I get the following error: </p>

<p>tmp*`, value = contr.funs[1 + isOF[nn]]) : 
  contrasts can be applied only to factors with 2 or more levels</p>

<p>I have found a solution for this problem, by running seperate loops for subcohorts with men and subcohorts with men and women by the following (simplified) code: </p>

<pre><code>men &lt;- c(1,6,15) # Cohort nrs that only contain men
menandwomen &lt;- c(2,3,4,5,7,8,9,10,11,12,13,14,16,17,18,19)

trenddpmodelm &lt;-list()
for(i in men) {
trenddpmodelm[[i]] &lt;- lm(BMI ~ age +  sex,                                               
data=subcohort[subcohort$centre_a==i, ],)
}

trenddpmodelmw &lt;-list()
for(i in menandwomen) {
trenddpmodelmw[[i]] &lt;- lm(BMI ~ age + sex,  
data=subcohort[subcohort$centre_a==i, ],)
}

trenddpmodel &lt;- c(list(trenddpmodelm[[1]]), list(trenddpmodelmw[[2]]),     list(trenddpmodelmw[[3]]), list(trenddpmodelmw[[4]]), list(trenddpmodelmw[[5]]), list(trenddpmodelm[[6]]), list(trenddpmodelmw[[7]]), list(trenddpmodelmw[[8]]), list(trenddpmodelmw[[9]]), list(trenddpmodelmw[[10]]), list(trenddpmodelmw[[11]]), list(trenddpmodelmw[[12]]), list(trenddpmodelmw[[13]]), list(trenddpmodelmw[[14]]), list(trenddpmodelm[[15]]), list(trenddpmodelmw[[16]]), list(trenddpmodelmw[[17]]), list(trenddpmodelmw[[18]]), list(trenddpmodelmw[[19]]))
</code></pre>

<p>After this step, I extract relevant information from the summaries and put this in a df to export to excel. 
My problem is that I will be running quite a lot of analyses, which will result in pages and pages of code. </p>

<p>My question is therefore: <strong>Is there a setting in R that I could use that allows non varying factors to be dropped from my lineair regression model in subcohorts where this is applicable?</strong> (similar to what happens in coxph; R gives a warning that the factor does not always vary, but the loop does run) </p>

<p>It is not like I cannot continue working without a solution, but I have been trying to find an answer to this question for days without succes and I think it must be possible somehow. Any advice is much appreciated :) </p>