# [Rd] ifelse can't return a list? Please explain (R-2.15.3)

Joshua Wiley jwiley.psych at gmail.com
Mon Mar 25 03:32:37 CET 2013

```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:
> I hope you are doing well.
>
> For me, this was an unexpected problem. I've hoped for quite a few
>
> 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:
>
>> x <- 1
>> y <- 2
>> z <- 3
>> a <- 4
>> b <- 5
>> c <- 6
>> list(x,y,z)
> [[1]]
> [1] 1
>
> [[2]]
> [1] 2
>
> [[3]]
> [1] 3
>
>> list(a,b,c)
> [[1]]
> [1] 4
>
> [[2]]
> [1] 5
>
> [[3]]
> [1] 6
>
>> ifelse(1, list(a,b,c), list(x,y,z))
> [[1]]
> [1] 4
>
>> ifelse(0, list(a,b,c), list(x,y,z))
> [[1]]
> [1] 1
>
>
>> sessionInfo()
> 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
> [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 :(
>
>> if (1) myvar <- list(a, b, c) else myvar <- list(x, y, z)
>> myvar
> [[1]]
> [1] 4
>
> [[2]]
> [1] 5
>
> [[3]]
> [1] 6
>
>> myvar <- if (1) list(a, b, c) else list(x, y, z)
>> myvar
> [[1]]
> [1] 4
>
> [[2]]
> [1] 5
>
> [[3]]
> [1] 6
>
>
> --
> Paul E. Johnson
> Professor, Political Science      Assoc. Director
> 1541 Lilac Lane, Room 504      Center for Research Methods
> University of Kansas                 University of Kansas
> http://pj.freefaculty.org               http://quant.ku.edu
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel

--
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://joshuawiley.com/
Senior Analyst - Elkhart Group Ltd.
http://elkhartgroup.com

```