# [R] How to use ifelse without invoking warnings

Ravi Varadhan r@v|@v@r@dh@n @end|ng |rom jhu@edu
Fri Oct 8 14:21:44 CEST 2021

```Thank you to Bert, Sarah, and John. I did consider suppressing warnings, but I felt that there must be a more principled approach.  While John's solution is what I would prefer, I cannot help but wonder why `ifelse' was not constructed to avoid this behavior.

Thanks & Best regards,
Ravi
________________________________
From: John Fox <jfox using mcmaster.ca>
Sent: Thursday, October 7, 2021 2:00 PM
Cc: R-Help <r-help using r-project.org>
Subject: Re: [R] How to use ifelse without invoking warnings

External Email - Use Caution

Dear Ravi,

It's already been suggested that you could disable warnings, but that's
risky in case there's a warning that you didn't anticipate. Here's a
different approach:

> kk <- k[k >= -1 & k <= n]
> ans <- numeric(length(k))
> ans[k > n] <- 1
> ans[k >= -1 & k <= n] <- pbeta(p, kk + 1, n - kk, lower.tail=FALSE)
> ans
[1] 0.000000000 0.006821826 0.254991551 1.000000000

BTW, I don't think that you mentioned that p = 0.3, but that seems
apparent from the output you showed.

I hope this helps,
John

--
John Fox, Professor Emeritus
McMaster University

On 2021-10-07 12:29 p.m., Ravi Varadhan via R-help wrote:
> Hi,
> I would like to execute the following vectorized calculation:
>
>    ans <- ifelse (k >= -1 & k <= n, pbeta(p, k+1, n-k, lower.tail = FALSE), ifelse (k < -1, 0, 1) )
>
> For example:
>
>
>> k <- c(-1.2,-0.5, 1.5, 10.4)
>> n <- 10
>> ans <- ifelse (k >= -1 & k <= n, pbeta(p,k+1,n-k,lower.tail=FALSE), ifelse (k < -1, 0, 1) )
> Warning message:
> In pbeta(p, k + 1, n - k, lower.tail = FALSE) : NaNs produced
>> print(ans)
> [1] 0.000000000 0.006821826 0.254991551 1.000000000
>
> The answer is correct.  However, I would like to eliminate the annoying warnings.  Is there a better way to do this?
>
> Thank you,
> Ravi
>
>
>       [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see