0

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
pvpaul
  • 15
  • 3
  • If you know the problem, you can use a logical test beforehand (using `if`), if you only know that there might be some errors, `tryCatch()` might be of help. – Kevin Cazelles Feb 27 '20 at 13:40
  • You can put the code line which can fail into a try block: `try({ ... }, silent=TRUE)`. – lambruscoAcido Feb 27 '20 at 13:40
  • @lambruscoAcido, this also worked perfect, thanks! – pvpaul Feb 27 '20 at 13:43
  • Though it is included at the end of `?try`, I'll just call it out: you should check the return value of `df <- try(filter(...))`, with something like `if (inherits(df, "try-error")) { do_something_here; }` to react accordingly. – r2evans Feb 27 '20 at 14:06

2 Answers2

0

I can't test it without a reproducible Example, but changing your code to:

for(x in c("B1", "B2", "B3")){
  for(z in c(1:5)){
     if(any(testb$column1 == x & testb$column2 == z)){
        df <- filter(testb, column1== x, column2 == z )

might do the trick.

Max Teflon
  • 1,760
  • 10
  • 16
0
for(x in c("B1", "B2", "B3")){
  for(z in c(1:5)){
    tryCatch({df <- filter(testb, column1== x, column2 == z)},
             next)
  }
}
Gwang-Jin Kim
  • 9,303
  • 17
  • 30