[R] need help in if else condition

Richard O'Keefe r@oknz @end|ng |rom gm@||@com
Wed Jul 10 17:18:42 CEST 2019


The answer here is that in "ifelse(a < 3, ......)" you ALWAYS expect "a" to
be
a vector because there would be no point in using ifelse if it weren't.
If you believe that "a" is or ought to be a single number, you write
  x <- if (a < 3) 1 else 2
The whole point of ifelse is to vectorise.


On Thu, 11 Jul 2019 at 01:47, Eric Berger <ericjberger using gmail.com> wrote:

> Or even
> > a <- 1:5
> > [lots of other code]
> > x <- ifelse( a < 3, 1, 2)
>
> The point (in this example) is that you might have introduced a bug because
> you forgot that 'a' is a vector.
> Looking (in isolation) at the assignment to 'x' you believe it's going to
> be a single number, either 1 or 2 (unless you know the "shape" of a).
> I've been burned by such issues.
>
>
> On Wed, Jul 10, 2019 at 4:42 PM Eric Berger <ericjberger using gmail.com> wrote:
>
> > For example, can you predict what the following code will do?
> > > a <- 1:5
> > > b <- c(2,3)
> > > ifelse( a < 3, 1, b)
> >
> >
> > On Wed, Jul 10, 2019 at 4:34 PM José María Mateos <chema using rinzewind.org>
> > wrote:
> >
> >> On Wed, Jul 10, 2019, at 04:39, Eric Berger wrote:
> >> > 1. The ifelse() command is a bit tricky in R. Avoiding it is often a
> >> good
> >> > policy.
> >>
> >> You piqued my curiosity, can you elaborate a bit more on this?
> >>
> >> --
> >> José María (Chema) Mateos || https://rinzewind.org
> >>
> >> ______________________________________________
> >> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> >> https://stat.ethz.ch/mailman/listinfo/r-help
> >> PLEASE do read the posting guide
> >> http://www.R-project.org/posting-guide.html
> >> and provide commented, minimal, self-contained, reproducible code.
> >>
> >
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list