If I type
ifelse(TRUE, rep(1,10), 0)
I get 1
instead of 1 1 1 1 1 1 1 1 1 1
.
Why? Is this a bug? How can I get the vector of ones?
If I type
ifelse(TRUE, rep(1,10), 0)
I get 1
instead of 1 1 1 1 1 1 1 1 1 1
.
Why? Is this a bug? How can I get the vector of ones?
Because ifelse
is vectorized, it:
returns a value with the same shape as test
Since your test is just a single element vector, your return is just the first element of rep(1, 10)
.
What you want is if
, which expects a single boolean, and then runs the following code, whatever it might be. If you want to return your else
statement, then we explicitly include else
as below.
if (TRUE) rep(1,10) else 0
#> [1] 1 1 1 1 1 1 1 1 1 1
You should know that ifelse
is vectorized. That means, your output dimensions aligns with the condition. In your code, since condition TRUE
is a single value, your output should also be a single value. That's why you get 1
instead of 1 1 1 1 1 1 1 1 1 1
.
You can try
> ifelse(rep(TRUE,10), 1, 0)
[1] 1 1 1 1 1 1 1 1 1 1
or
> unlist(ifelse(TRUE, list(rep(1, 10)), 0))
[1] 1 1 1 1 1 1 1 1 1 1