Loop is not walking, does not leave the first position

Asked

Viewed 42 times

-1

f3 <- function(n)  {
  dados <- rnorm(n, mean = 0, sd = 1)
  matrizB <- matrix(0,2, n)
  for (i in 1:length(dados)) {
    s <- 1
    if (i <= 0.2) {
      matrizB[1,] <- 1
      matrizB[2,] <- 0.2
    }
    if (i > 0.2 | i<=0.7) {
      matrizB[1,] <- 2
      matrizB[2,] <- 0.5
    }
    else {
      matrizB[1,] <- 3
      matrizB[2,] <- 0.3
      s <- s + 1
    }
  return(matrizB)
  }
}

f3(3) # o loop não está caminhando, não sai da primeira posição

The exercise was: Consider the random variable Y with the following probability distribution:

     y 1   2   3
P(Y=y) 0,2 0,5 0,3

It is possible to generate a value of this probability distribution initially generating an X value of a uniform distribution(0,1). If X 0, 2 then Y = 1, if 0, 2 < X 0, 7 then Y = 2, if X > 0, 7 then Y = 3. a) Using and generating values of the Uniform distribution(0,1), do a function to generate a sample of size n (only argument of the function) of the probability distribution of Y.

2 answers

1

Here’s an R-based solution without cycles for. Utilizes cumsum and findInterval to determine the values of y.

f3 <- function(n, fmp){
  prob_acum <- cumsum(fmp)
  p <- runif(n)
  findInterval(p, c(0, prob_acum), rightmost.closed = TRUE, all.inside = TRUE)
}

set.seed(2021)

FMP <- c(0.2, 0.5, 0.3)  # A função massa de probabilidade
x <- f3(1e6, FMP)        # teste com n = 1e6

tbl <- table(x)          # verificar se as proporções
                         # correspondem às probabilidades
tbl/sum(tbl)
#x
#       1        2        3 
#0.199352 0.500465 0.300183 

0

You are asking to return matrix B every time the loop is executed, the first time the loop rotates it will already come out of the loop. If your goal is to make the f function return something, remove the return(matrizB) from inside the for. Another point, try to do tests on your values, so you seem to debug, as for example check that the data size, making a print(length(dados)). (If your language is js, use console.log)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.