How to improve my code?

I want to show law of large numbers. I simulate a sample of size n=1000, 1000, 10000 respectively from Poisson variates with mean 5, 10, 15, and 20. Then I estimate E(sqrt(x)) and Var(sqrt(x)). My current codes are:

f <- function(n, lambda) {
  E <- mean(sqrt(rpois(n, lambda)))
  VAR <- var(sqrt(rpois(n, lambda)))
  return(c(E, VAR))
}

f(1000, 5)
f(1000, 10)
f(1000, 15)
f(1000, 20)

f(10000, 5)
f(10000, 10)
f(10000, 15)
f(10000, 20)

f(100000, 5)
f(100000, 10)
f(100000, 15)
f(100000, 20)

The outputs are not very in a beautiful way:
[1] 2.1811702 0.2771724
[1] 3.1130539 0.2616986
[1] 3.8524663 0.2417407
[1] 4.4322371 0.2531221
[1] 2.1679419 0.2881696
[1] 3.1306374 0.2568755
[1] 3.8376813 0.2554475
[1] 4.4458512 0.2567878
[1] 2.1715152 0.2858644
[1] 3.1164014 0.2612395
[1] 3.8393476 0.2577202
[1] 4.4426835 0.2541482

You can try something like this:

set.seed(seed = 91647)

Poisson_WLLN <- function(sample_size, simulated_lambda)
{
    simulated_data <- sqrt(x = rpois(n = sample_size,
                                     lambda = simulated_lambda))
    expectation <- mean(x = simulated_data)
    variance <- var(x = simulated_data)
    paste("E:", round(x = expectation,
                      digits = 2),
          "V:", round(x = variance,
                      digits = 2))
}

Vectorised_Poisson_WLLN <- Vectorize(FUN = Poisson_WLLN)

simulated_sample_sizes <- c(100, 1000, 10000)
simulated_lambdas <- c(5, 10, 15, 20)

outer(X = simulated_sample_sizes,
      Y = simulated_lambdas,
      FUN = Vectorised_Poisson_WLLN)
#>      [,1]              [,2]              [,3]              [,4]             
#> [1,] "E: 2.23 V: 0.26" "E: 3.15 V: 0.33" "E: 3.81 V: 0.26" "E: 4.47 V: 0.29"
#> [2,] "E: 2.17 V: 0.33" "E: 3.12 V: 0.28" "E: 3.82 V: 0.26" "E: 4.44 V: 0.25"
#> [3,] "E: 2.17 V: 0.28" "E: 3.12 V: 0.26" "E: 3.84 V: 0.25" "E: 4.44 V: 0.25"

Created on 2020-12-25 by the reprex package (v0.3.0)

Hope this helps.

1 Like

Thanks. Can you tell me what the meaning of "Vectorised_Poisson_WLLN <- Vectorize(FUN = Poisson_LLN)" is?

When you pass X and Y to outer, they are replicated to match length of each other. Then for each pair of X and Y, FUN is applied.

If your FUN is not vectorised, it'll take the X and Y as a single input and try to process. But what you want is to apply FUN on each pair independently of other pairs. That's why FUN needs to vectorised, which can be applied on each pair separately. So, what Vectorise does is basically create a new function, which applies your old function on element wise on the cartesian product of the X and Y.

Hope this helps.

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.