ifelse not working as expected in R

Jake Jackson

I am trying to create a vectorial function in R using the command ifelse as follows

temp <- function(p){
ifelse(p < 0.5 *(1 + 0.5), (1 + 0.5) * qnorm(p/(1 +0.5)), (1 - 0.5) * qnorm((p - 0.5)/(1 - 0.5)))
}

The function works well with scalar values, for example

> temp(0.1)
[1] -2.251629
> temp(0.9)
[1] 0.4208106

but not for vectors:

> temp(c(0.1,0.9))
[1] -2.2516289  0.4208106
Warning message:
In qnorm((p - 0.5)/(1 - 0.5)) : NaNs produced

The weird thing is that it returns the right answer, but indicating a warning.

What am I doing wrong? It seems that the ifelse is evaluating both functions in all the entries of the vector p, which is supposed to be avoided with this command.

mgriebe

ifelse is basically doing this:

p<- c(.1,.9)
a<-(1 + 0.5) * qnorm(p/(1 +0.5))
b<- (1 - 0.5) * qnorm((p - 0.5)/(1 - 0.5))
c<-NULL
c[which(p < 0.5 *(1 + 0.5))] <-a[which(p < 0.5 *(1 + 0.5))]
c[which(!(p < 0.5 *(1 + 0.5)))] <-b[which(!(p < 0.5 *(1 + 0.5)))]

That is, it creates a vector for 'yes' and a vector for 'no'. The 'no' vector it creates throws the warning.

The examples in the documentation allude to this.

x <- c(6:-4)
sqrt(x)  #- gives warning
sqrt(ifelse(x >= 0, x, NA))  # no warning

## Note: the following also gives the warning !
ifelse(x >= 0, sqrt(x), NA)

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

AJAX call is not working as expected

分類Dev

jQuery .when().then() not working as expected

分類Dev

.vimrc file not working as expected

分類Dev

*ngIf not working as expected with observable

分類Dev

ItemIsAutoTristate flag not working as expected

分類Dev

KeyboardAvoidingView not working as expected on IOS

分類Dev

PowerShell variables not working as expected

分類Dev

XPath logical 'and' not working as expected?

分類Dev

CancellationTokenSource not working as expected on a TaskCompletionSource

分類Dev

string formatting not working as expected

分類Dev

Why is .on() Not working as expected in jquery?

分類Dev

Tuples in Scala not working as expected

分類Dev

strpos() not working as expected

分類Dev

PHP Dateformat not working as expected

分類Dev

Update not working as expected

分類Dev

$("#form").submit(); is not working as expected

分類Dev

Prototype is not working as expected

分類Dev

LIKE and Equals not working as expected

分類Dev

Regex is not working as expected in javascript

分類Dev

angularjs service not working as expected

分類Dev

NSTask not working as expected / hoped for

分類Dev

Routing not working as expected in CodeIgniter

分類Dev

mhddfs not working as expected

分類Dev

Python: If...and... not working as expected

分類Dev

timeout for ngShow not working as expected

分類Dev

extglob negation not working as expected

分類Dev

LIKE query not working as expected

分類Dev

boostrap clearfix not working as expected

分類Dev

AltBeacon: ranging not working as expected