Marcelo
Marcelo

Reputation: 3

Creating an uniform distribution function

I trying to create an uniform distribution function in R.


fx_uniforme <- function(x,a,b) {
  Fx <- 0
  for (i in 0:x) {
    Fx <- Fx + (a:(b-a+1))/(b-a+1)
    
}
  
  return(Fx)
  
}

uniforme_sim <- function(F,...) {
  x <- 0
  u <- runif(1)
  while (F(x, ...) < u) {
  x <- x + 1
  }
  return(x)
}

uniforme_sim(fx_uniforme,1,10)

m <- 1000
a <- 1
b <- 10 
Ya <- array(NA, dim = m)
for (i in 1:m) {
  
 Ya[i] <- uniforme_sim(fx_uniforme,a,b)

}
Ya

barplot(table(Ya))

When I plot instead of running from 1 to 10 it´s running from 0 to 9. What shold I do to fix this problem?

Upvotes: 0

Views: 221

Answers (1)

Brian Montgomery
Brian Montgomery

Reputation: 2414

This can be fixed by substituting return(1 + x) for return(x) in the uniforme_sim function.

Also, I think you want Fx <- Fx + 1/(b-a+1) in the fx_uniforme function to eliminate the warnings "the condition has length > 1 and only the first element will be used"

More importantly, you need to recognize that R stores every variable as a vector and most of the functions will work on vectors. Then take advantage of that to eliminate all the looping you have in here.

You can replace all this with:

m <- 1000
a <- 1
b <- 10 
Ya <- sample(a:b, m, replace = TRUE)

barplot(table(Ya))

Upvotes: 1

Related Questions