![](/img/trans.png)
[英]“the condition has length > 1 and only the first element will be used” error
[英]Error in the if function: the condition has length > 1 and only the first element will be used
我想使用 1000 次重復繪制 L 波浪號的直方圖,其中 γ = 0.9*\\sqrt{2logn} 且 n=1000。 我為 L 編寫了函數,並為 L 波浪號編寫了一個“for, if”循環。 但是我在“if”循環中遇到錯誤,並且當我使用“replicate”生成直方圖時,它只給了我 1000 個相同的值。
你能幫我解決這個錯誤以及如何使用 1000 次重復來繪制直方圖嗎? 謝謝!
錯誤:“在 if (data[i, ] < replica(n, sqrt(2 * log(n)))) { : 條件長度 > 1 並且只使用第一個元素”
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)))
您遇到該錯誤是因為您只能在if (...)
評估單個 T/F。 然而, data[1, ] < ...
是一個向量化的評估,它返回一個長度為 n 的 T/F 向量(即上面的例子為 1000)。 盡管如此,我認為您的第二個函數( est_L
)與該圖像中顯示的方程不匹配。 請考慮以下實現:
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))
}
那么你就可以
hist(replicate(1000, L_tilde(1000)))
輸出
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.