I created a loop for a rather repetitive "function" or piece of code.
I do a dplyr filter of the data set based on two variables. Then I make a linear model, calculate the means and do a LSD test.
The loop I made fills in the variables in the filter.
for(x in c("B1", "B2", "B3")){
for(z in c(1:5)){
df <- filter(testb, column1== x, column2 == z )
#rest of functions here
The loop works fine. Only problem I have is when the loop tries to filter x: B2 with z: 5, since this combination does not exist in the data set. I get the following error:
Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) :
contrasts can be applied only to factors with 2 or more levels
I know exactly why it creates an error, since the factor has column 2 z=5 does not exist. I would like the loop to continue to the next variable of columns 1 and 2, if this occurs, so go to x:B3 and z: 1.
The code works fine when I use
for(z in c(1:4)){
But I miss the combinations x:B1 and x:B3 with z:5.
Later one I would like to do more variables from column1, but there will be a lot more mismatching with the combinations of x and z.
Anyone any tips?