'Function "rep" inside an "ifelse" does not return any repetition [duplicate]

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?

r


Solution 1:[1]

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

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 caldwellst
Solution 2