Why can't -qnorm in sapply?

> sapply(c(0.05,0.01),function(k){-qnorm(k)}) [1] 1.644854 2.326348 > -sapply(c(0.05,0.01),qnorm) [1] 1.644854 2.326348 

but the following cannot work, why -qnorm cannot work in sapply?

sapply (with (0.05,0.01), - qnorm)
Error in -qnorm: invalid argument for unary operator

+3
source share
2 answers

The cause of the problem is that -qnorm(.) Is actually part of the two functions. First you compute qnorm(.) , Then you take negative .

sapply expects a single function.

When using sapply( <..>, -qnorm) R tries to calculate the minus qnorm function, which makes no sense to the functions.
(Just enter -qnorm and you will get the same error.)

The reason -qnorm(k) is because R calculates qnorm(k) to get a number, and then takes a negative value for that number.

Similarly, sapply(<..>, qnorm) gives a vector. Therefore, when you add a negative sign in front of it, you get the desired result.

+2
source

Compose is good for things like this:

 require(functional) sapply(c(0.05,0.01), Compose(qnorm, `-`)) [1] 1.644854 2.326348 

Please note that back quotes around - are required here.

+5
source

Source: https://habr.com/ru/post/955215/


All Articles