[R] need help in if else condition

Eric Berger er|cjberger @end|ng |rom gm@||@com
Wed Jul 10 18:04:21 CEST 2019


Of course the behavior of ifelse is predictable.
My point was that for newb's (I was one once) you can get burned if you
don't appreciate that ifelse is vectorized.
Especially if you have some "muscle memory" from using ifelse() in Excel.

On Wed, Jul 10, 2019 at 6:55 PM Richard O'Keefe <raoknz using gmail.com> wrote:

> Expectation: ifelse will use the same "repeat vectors to match the longest"
> rule that other vectorised functions do.  So
> a <- 1:5
> b <- c(2,3)
> ifelse(a < 3, 1, b)
> => ifelse(T T F F F <<5>>, 1 <<1>>, 2 3 <<2>>)
> => ifelse(T T F F F <<5>>, 1 1 1 1 1 <<5>>, 2 3 2 3 2 <<5>>)
> => 1 1 2 3 2
> and that is indeed the answer you get.  Entirely predictable and
> consistent with
> other basic operations in R.
>
> The only tricky thing I see is that R has
> a strict vectorised  ifelse(logical.vector, some.vector, another.vector)
> AND
> a non-strict non-vectorised if (logical.scalar) some.value else
> another.value
> AND
> a statement form if (logical.scalar) stmt.1; else stmt.2;
>
>
> On Thu, 11 Jul 2019 at 01:47, Eric Berger <ericjberger using gmail.com> wrote:
>
>> For example, can you predict what the following code will do?
>> > a <- 1:5
>> > b <- c(2,3)
>> > ifelse( a < 3, 1, b)
>>
>>
>> On Wed, Jul 10, 2019 at 4:34 PM José María Mateos <chema using rinzewind.org>
>> wrote:
>>
>> > On Wed, Jul 10, 2019, at 04:39, Eric Berger wrote:
>> > > 1. The ifelse() command is a bit tricky in R. Avoiding it is often a
>> good
>> > > policy.
>> >
>> > You piqued my curiosity, can you elaborate a bit more on this?
>> >
>> > --
>> > José María (Chema) Mateos || https://rinzewind.org
>> >
>> > ______________________________________________
>> > R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> > https://stat.ethz.ch/mailman/listinfo/r-help
>> > PLEASE do read the posting guide
>> > http://www.R-project.org/posting-guide.html
>> > and provide commented, minimal, self-contained, reproducible code.
>> >
>>
>>         [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list