Home > Back-end >  Output from which() statement suppressed in if statement
Output from which() statement suppressed in if statement

Time:09-27

I have a data frame with the string "BLQ" in some of the cells. I can find out where these occur using:

which(df == "BLQ", arr.ind = TRUE)

In a particular example I am interested in, the length of the vector above yields

> length(which(df == "BLQ", arr.ind = TRUE))
[1] 492

If I execute the following:

  which(df == "BLQ", arr.ind = TRUE)
  stop("BLQ still present")

I will see all entries (rows and columns) where "BLQ" occurs and the program stops with the desired output:

Error: BLQ still present

But if I have the above enclosed in an IF statement:

if (length(which(df == "BLQ", arr.ind = TRUE)) != 0){
  which(df == "BLQ", arr.ind = TRUE)
  stop("BLQ still present")
}

The output from the which function is suppressed and I just see:

Error: BLQ still present

Why is that?

Thank you for your help.

CodePudding user response:

Any time we use { }, we are creating a new enclosure. By default, R returns the result of an enclosure's last statement. In your example:

if (length(which(df == "BLQ", arr.ind = TRUE)) != 0){
  which(df == "BLQ", arr.ind = TRUE)
  stop("BLQ still present")
}

The which function returns an array of indices, but it isn't the last statement in the enclosure. The stop function, which is, returns nothing, which is why we see nothing when this code is run.

Conversely, the following code will return the indices as you expected, because which is the last statement:

if (length(which(df == "BLQ", arr.ind = TRUE)) != 0){
  which(df == "BLQ", arr.ind = TRUE)
}

You can force the output of which to appear with a print statement:

if (length(which(df == "BLQ", arr.ind = TRUE)) != 0){
  print(which(df == "BLQ", arr.ind = TRUE))
  stop("BLQ still present")
}

Incidentally, you can even capture the final result of the enclosure as you would any other function, i.e.:

a <- if (...) { 
  2 
}

a
[1] 2
  
  • Related