Reputation: 75
I have two statistics given by
I want to use 1000 replicates to draw the histogram of L tilde where γ = 0.9*\sqrt{2logn} with n=1000. I wrote function for L and a "for, if" loop for L tilde. But i get the error in the "if" loop and also when I use "replicate" to generate histogram it gives me only 1000 the same values.
Can you help me with the error and how to use 1000 replicates to draw the histogram? Thank you!
Error: "In if (data[i, ] < replicate(n, sqrt(2 * log(n)))) { : the condition has length > 1 and only the first element will be used"
n=10^3
del = 0.9*sqrt(2*log(n))
data <- matrix(replicate(n,rnorm(n,0,1)),nrow = n)
L = n^{-1}*sum(exp(del*data[1,]-0.5*del^2))
#L tilde
est_L <- function(n){
est=0
for (i in 1:n){
if (data[i,]<sqrt(2*log(n))){
est = est + n^{-1}*sum(exp(del*data[1,]-0.5*del^2))
}
return(est)
}
}
#repeat 1000 times
hist(replicate(1000,est_L(10^3)))
Upvotes: 0
Views: 526
Reputation: 8844
You got that error because you can only evaluate a single T/F in if (...)
. However, data[1, ] < ...
is a vectorised evaluation that returns a T/F vector of a length n (i.e. 1000 for your case above). Nevertheless, I think your second function (est_L
) does not match the equation shown in that image. Consider the following implementation instead:
L <- function(n) {
del <- 0.9 * sqrt(2 * log(n))
data <- rnorm(n)
mean(exp(del * data - 0.5 * del * del))
}
L_tilde <- function(n) {
del <- 0.9 * sqrt(2 * log(n))
data <- rnorm(n)
mean(exp(del * data * ifelse(data < sqrt(2 * log(n)), 1, 0) - 0.5 * del * del))
}
Then you can just
hist(replicate(1000, L_tilde(1000)))
Output
Upvotes: 1