[R] if-else that returns vector

Christofer Bogaso bog@@o@chr|@to|er @end|ng |rom gm@||@com
Fri Oct 13 11:38:30 CEST 2023


This is very interesting. Thanks for sharing.

On Fri, Oct 13, 2023 at 10:25 AM Richard O'Keefe <raoknz using gmail.com> wrote:
>
> ?ifelse
> 'ifelse' returns a value with the same shape as 'test' which is
>      filled with elements selected from either 'yes' or 'no' depending
>      on whether the element of 'test' is 'TRUE' or 'FALSE'.
>
> This is actually rather startling, because elsewhere in the
> S (R) language, operands are normally replicated to the length
> of the longer.  Thus
>     c(1,2,3)*10 + c(5,6)
> first (notionally) replicates 10 to c(10,10,10)
> and then c(5,6) to c(5,6,5), yielding c(15,26,35).
> And this *does* happen, sort of.
> > ifelse(c(F,T,F), c(1,2,3), c(5,6))
> => 5 2 5.
> But it *doesn't* apply to the test.
>
> There's another surprise.  Years ago I expected that
> all three arguments would be evaluated, then length
> adjusted, and then processing would be done.
> But the 2nd argument is evaluated (in full) if and only
> if some element of the test is true,
> and the 3rd argument is evaluated (in full) if and oly
> if some element of the test is false.
> ifelse(c(NA,NA), stop("true"), stop("false"))
> => c(NA,NA).
>
> At any rate, what you want is if (<test>) <tp> else <fp>
>
>
>
> On Fri, 13 Oct 2023 at 09:22, Christofer Bogaso <bogaso.christofer using gmail.com> wrote:
>>
>> Hi,
>>
>> Following expression returns only the first element
>>
>> ifelse(T, c(1,2,3), c(5,6))
>>
>> However I am looking for some one-liner expression like above which
>> will return the entire vector.
>>
>> Is there any way to achieve this?
>>
>> ______________________________________________
>> 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.



More information about the R-help mailing list