[R] difference between ifelse and if...else?

Duncan Murdoch murdoch.duncan at gmail.com
Wed Dec 13 17:37:21 CET 2017


On 13/12/2017 10:31 AM, Jinsong Zhao wrote:
> Hi there,
> 
> I don't know why the following codes are return different results.
> 
>   > ifelse(3 > 2, 1:3, length(1:3))
> [1] 1
>   > if (3 > 2) 1:3 else length(1:3)
> [1] 1 2 3
> 
> Any hints?

The documentation in the help page ?ifelse and ?"if" explains it pretty 
clearly.  Think of ifelse() as a function with vector inputs and a 
vector output, and if() as a flow control construction.

Duncan Murdoch



More information about the R-help mailing list