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

Paul Johnson pauljohn32 at gmail.com
Mon Mar 25 03:21:40 CET 2013


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:

> 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
 [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 :(

> 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



More information about the R-devel mailing list