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



--
Patrick Burns
pbu...@pburns.seanet.com
twitter: @burnsstat @portfolioprobe
http://www.portfolioprobe.com/blog
http://www.burns-stat.com
(home of:
 'Impatient R'
 'The R Inferno'
 'Tao Te Programming')

______________________________________________
R-devel@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel

Reply via email to