Different output when running a line inside vs. outside an ifelse() statement

Viewed 50

I am trying to run a simple command but no idea why the output is different when running it inside vs outside an ifelse() function. The function condition evaluates to FALSE, so the output should be the exact same.

However, when running it alone, the output is 0 0 1 1 0 1 0 1 NA (as desired) but from the ifelse() function, the output is 0 (not desired).

library(dplyr)
library(zoo)

x <- c(0, 1, 1, 0, 0, 1, 0, 1, 0)
del <- 2

dplyr::lead(zoo::rollsum(x, del - 1, fill = NA, align = "left")) == 0
[1] FALSE FALSE  TRUE  TRUE FALSE  TRUE FALSE  TRUE    NA

ifelse(del == 1, -1, dplyr::lead(zoo::rollsum(x, del - 1, fill = NA, align = "left")) == 0)
[1] FALSE

I would appreciate any help on why this is happening! Never seen something like this before. The outcomes of the ifelse() have different lengths depending on whether the condition is evaluated as true or false, but I don't see why this would cause a truncation of the longer output.

1 Answers

The code should be using if, not ifelse. From ?ifelse it says the following where test is the first argument of ifelse.

‘ifelse’ returns a value with the same shape as ‘test’

In the question test is del == 1 which is a logical scalar so the result will be one too.

Also rollapply can use list(1:(del-1)) to refer to offsets 1, 2, ..., del-1 where positive offsets are ahead. This seems cleaner since it direclty implements what is wanted rather than fixing it up later and it also uses fewer packages.

library(zoo)

del <- 2
if (del == 1) -1 else rollapply(x == 0, list(1:(del-1)), all, fill = NA)
## [1] FALSE FALSE  TRUE  TRUE FALSE  TRUE FALSE  TRUE    NA
Related