Alex
Alex

Reputation: 15

How to compute the probability given a data set in R?

I have a vector with values which distribution is unknown and i want to create another vector with the probabilities of the values i have. eg.

I have

v <- c(e1, e2, ... , ei)

and i want to create

p <- c(P(e1), P(e2), ... , P(ei)) 

How can i do this in R?

Upvotes: 1

Views: 2579

Answers (1)

markdly
markdly

Reputation: 4544

As you want to create a vector the same length as the vector of values, you could do something like:

p <- sapply(v, function(x) length(which(x == v))/length(v))

Example using letters as values

set.seed(123)
v = sample(letters[1:4], 10, replace = TRUE)

p <- sapply(v, function(x) length(which(x == v))/length(v))
p
#>   b   d   b   d   d   a   c   d   c   b 
#> 0.3 0.4 0.3 0.4 0.4 0.1 0.2 0.4 0.2 0.3

Upvotes: 1

Related Questions