Skip to content

ifelse can't return a list? Please explain (R-2.15.3)

3 messages · Paul Johnson, Joshua Wiley, Patrick Burns

#
I hope you are doing well.

For me, this was an unexpected problem. I've hoped for quite a few
wrong things today, but I'm only asking you about this one. Why does

ifelse(1, list(a, b, c), list(x, y, z))

return a list with only a, not list(a, b, c) as I hoped.  I wish it
would either
cause an error or return the whole list, not just the first thing.

Working example:
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3
[[1]]
[1] 4

[[2]]
[1] 5

[[3]]
[1] 6
[[1]]
[1] 4
[[1]]
[1] 1
R version 2.15.3 (2013-03-01)
Platform: x86_64-pc-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8
 [7] LC_PAPER=C                 LC_NAME=C
 [9] LC_ADDRESS=C               LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] rockchalk_1.5.5.10 car_2.0-16         nnet_7.3-5         MASS_7.3-23

loaded via a namespace (and not attached):
[1] compiler_2.15.3 tools_2.15.3


I realize I can code around this, but I'm just curious about why
ifelse hates me so much :(
[[1]]
[1] 4

[[2]]
[1] 5

[[3]]
[1] 6
[[1]]
[1] 4

[[2]]
[1] 5

[[3]]
[1] 6
#
Hi Paul,

Wonder why this is an R devel thing?

ifelse is vectorized----there should be logical conditions matching
the length of the output.

ifelse(c(1, 1, 1), list(a=2, b=3, c=4), list(d=1, e=2, f=3))

otherwise it is truncated.  Also note that both results have to be
valid, because both are typically evaluated.

Cheers,

Josh
On Sun, Mar 24, 2013 at 7:21 PM, Paul Johnson <pauljohn32 at gmail.com> wrote:

  
    
#
When you what you hope for turns out to
be wrong, then have a look at 'The R Inferno'.

http://www.burns-stat.com/documents/books/the-r-inferno/

It does talk about 'ifelse'.

Pat
On 25/03/2013 02:21, Paul Johnson wrote: