Home > other >  Function in R probabilities
Function in R probabilities

Time:06-06

Write a function get_probs (taking as input a numeric vector) that is first computing the rank (you can use the R function rank for this) and then divides it by the number of observations to obtain the empiric probabilities. These probabilities should be returned as a vector.

I did not totally get every part of the task. Could someone help me out, please?

CodePudding user response:

First I create a random numeric vector using c with some numbers. To get the empiric probabilities you can use rank and divide by the number of observations in your vector using length. This will calculate the number of observations, in this case 6. After that you can use your created function and call the numeric vector in your function which returns the probabilities as a vector. You can use the following code:

vector <- c(1,0,-1,1,1,0)

get_probs <- function(vector) {
  probs <- rank(vector)/length(vector)
  return(probs)
}
print(get_probs(vector))

Output:

[1] 0.8333333 0.4166667 0.1666667 0.8333333 0.8333333 0.4166667

Quantiles

You can use the function quantile like this:

quantile(get_probs(vector))

Output:

       0%       25%       50%       75%      100% 
0.1666667 0.4166667 0.6250000 0.8333333 0.8333333 
  • Related