问题描述
我正在尝试使用命令 ifelse
在R中创建一个矢量函数,如下所示
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
但不适用于矢量:
> 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.
我做错了什么?似乎 ifelse
正在评估向量 p
的所有条目中的两个函数,这应该是避免的使用此命令。
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.
推荐答案
ifelse
基本上是这样做的:
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)))]
也就是说,它为'yes'创建了一个向量,为'no'创建了一个向量。它创建的'no'向量会抛出警告。
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)
这篇关于如果在R中没有按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!