Skip to content

if-else that returns vector

6 messages · Christofer Bogaso, Ben Bolker, Jeff Newmiller +2 more

#
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?
#
how about

if(T) c(1,2,3) else c(5,6)

?
On 2023-10-12 4:22 p.m., Christofer Bogaso wrote:
#
What a strange question... ifelse returns a vector (all data in R is vectors... some have length 1, but length zero is also possible, as are longer vectors) that is exactly as long as the logical vector that you give it, filled with elements from the respective positions in the vectors supplied in the second and third arguments. Because your logical vector is length 1, you only get a vector with the first element of the second argument.

If you want to choose between one of two vectors considered wholly, then "if" is what you need:

result <- if (TRUE) c(1,2,3) else c(5,6)
On October 12, 2023 1:22:03 PM PDT, Christofer Bogaso <bogaso.christofer at gmail.com> wrote:

  
    
#
?s 21:22 de 12/10/2023, Christofer Bogaso escreveu:
Hello,

I don't like it but


ifelse(rep(T, length(c(1,2,3))), c(1,2,3), c(5,6))


maybe you should use


max(length(c(1, 2, 3)), length(5, 6)))


instead, but it's still ugly.

Hope this helps,

Rui Barradas
#
?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.
=> 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 at gmail.com>
wrote:

  
  
#
This is very interesting. Thanks for sharing.
On Fri, Oct 13, 2023 at 10:25?AM Richard O'Keefe <raoknz at gmail.com> wrote: