[R] Conditional Execution Error

David L Carlson dcarlson at tamu.edu
Thu Aug 11 22:59:40 CEST 2016


And as a function, ifelse() wants to return a replacement value and when h < j is FALSE, your code does not return anything. Like most things in R, you can bend it to your will, but there will probably be consequences:

> h <- 10
> j <- -5
> ifelse(h < j, "statement is true", {while(h >= j) {
+ print(h)
+ h <- h - 1 }
+ "done"}
+ )
[1] 10
[1] 9
[1] 8
[1] 7
[1] 6
[1] 5
[1] 4
[1] 3
[1] 2
[1] 1
[1] 0
[1] -1
[1] -2
[1] -3
[1] -4
[1] -5
[1] "done"


-------------------------------------
David L Carlson
Department of Anthropology
Texas A&M University
College Station, TX 77840-4352

-----Original Message-----
From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of MacQueen, Don
Sent: Thursday, August 11, 2016 3:39 PM
To: Steve Murray; r-help at r-project.org
Subject: Re: [R] Conditional Execution Error

The simplest explanation is that
  ifelse( , , )
is not designed or intended to be an alternative way to do
  if () {} else {}

ifelse is not designed for conditional execution.

Read the help page for ifelse for an explanation of what it IS designed to
do.

-Don

-- 
Don MacQueen

Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550
925-423-1062





On 8/11/16, 1:24 PM, "R-help on behalf of Steve Murray"
<r-help-bounces at r-project.org on behalf of smurray444 at hotmail.com> wrote:

>Dear all,
>
>
>Please could someone explain why 'Version 1' of the code below works, but
>'Version 2' produces an error (albeit following the correct output)?
>
>
>#Version 1
>
>h <- 10
>j <- -5
>
>if(h < j) {
>print("statement is true")
>} else {
>while (h >= j) {
>print(h)
>h <- h - 1
>}
>}
>
>
>#Version 2
>
>h <- 10
>j <- -5
>
>ifelse(h < j, "statement is true", while(h >= j) {
>print(h)
>h <- h - 1
>}
>)
>
>
>
>If anyone has an explanation and solution (for avoiding the error), then
>I'd be pleased to hear it.
>
>
>Many thanks,
>
>Steve
>
>
>	[[alternative HTML version deleted]]
>
>______________________________________________
>R-help at 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.

______________________________________________
R-help at 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.



More information about the R-help mailing list