Re: [Rd] ifelse

From: Marc Schwartz <marc_schwartz_at_comcast.net>
Date: Mon, 18 Aug 2008 19:09:48 -0500

on 08/18/2008 06:35 PM Heikki Kaskelma wrote:
> I find it slightly surprising, that
>
> ifelse(TRUE, character(0), "")
>
> returns NA instead of character(0).
>
> [WNT 2.6.2 Patched]

Time to upgrade... :-)

The same behavior is in:

  R version 2.7.2 beta (2008-08-16 r46368)

The reason for this is that the internal code for ifelse() has:

    if (any(test[!nas]))

        ans[test & !nas] <- rep(yes, length.out = length(ans))[test &
            !nas]

where the key code is:

  rep(yes, length.out = length(ans))

In this case, 'yes' is character(0) and 'ans' is TRUE.

Thus, you get:

  > rep(character(0), length.out = length(TRUE))   [1] NA

This behavior is documented in ?rep, where in the Details section you will find:

"If x has length zero and length.out is supplied and is positive, the values are filled in using the extraction rules, that is by an NA of the appropriate class for an atomic vector (0 for raw vectors) and NULL for a list. "

Thus:

> class(rep(character(0), length.out = length(TRUE)))
[1] "character"

which shows that the NA that is returned is of class character, which is the class for character(0).

HTH, Marc Schwartz



R-devel_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel Received on Tue 19 Aug 2008 - 00:10:45 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 19 Aug 2008 - 07:37:21 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-devel. Please read the posting guide before posting to the list.

list of date sections of archive