一些事情:
juljo 在循环之前初始化向量是正确的,他们做了一些其他的更正,但我认为他们的代码只有在你已经建立的情况下才有效:
j <- 1
否则,juljo 的代码就会中断。
此外,您的代码不需要“&&”即可工作。只需将 j
j <- 1
x <- c(.01,.05,.10,.20,.25) # observed defect rates
atmost2 <- as.numeric(1:length(x)) # this initializes the vector to a predetermined length which may help with very large loops
for(i in 1:length(x)) {
if(x < 1){
atmost2[i] <- dbinom(0,size=10,prob=x[j])+ # note that the double brackets are gone
dbinom(1,size=10,prob=x[j])+
dbinom(2,size=10,prob=x[j])
}
j <- j + 1 # I think you want j to increment outside the if statement
}
atmost2
此代码执行“某些操作”,但有一些警告,我不确定您要做什么。
您也可以跳过添加 dbinom 并改为:
j <- 1
x <- c(.01,.05,.10,.20,.25) # observed defect rates
atmost2 <- as.numeric(1:length(x)) # this initializes the vector to a predetermined length which may help with very large loops
for(i in 1:length(x)) {
if(x < 1){
atmost2[i] <- sum(dbinom( 0:2 , size=10,prob=x[j])) #dbinom will give a vector that can be summed
}
j <- j + 1 # I think you want j to increment outside the if statement
}
atmost2
但我认为使用 j 迭代器可能是其他编程语言的习惯。注意使用循环但没有 j 的相同输出:
x <- c(.01,.05,.10,.20,.25) # observed defect rates
atmost2 <- as.numeric(1:length(x)) # this initializes the vector to a predetermined length which may help with very large loops
for(i in 1:length(x)) {
if(x < 1){
atmost2[i] <- sum(dbinom(0:2,size=10,prob=x[i]))
}
}
atmost2
这些都产生相同的输出:
> atmost2
[1] 0.9998862 0.9884964 0.9298092 0.6777995 0.5255928
但我有后续问题:
atmost2 应该与 x 长度相同吗?
您是否使用 x 中的值作为概率?那么,atmost2 是基于 x[i] 的值的 dbinom 概率之和?
它必须是一个循环吗? R 很好地使用了向量,因此 apply 函数可能会有所帮助。您可能会发现 lapply 在这里很有用。
?apply 可能会让你开始
?lapply 将给出其他应用函数的描述。
所以你的代码可能看起来像这样
x <- c(.01, .05, .10, .20, .25)
atmost2 <- as.numeric(1:length(x))
atmost2 <- lapply(x, function(x) sum(dbinom( 0:2 , size = 10, prob = x)))
atmost2 # this is a list, not a vector
lapply 函数如下所示:
应用于列表中的项目,'x',一个函数。
在这种情况下,该函数是一个匿名函数“sum(dbinom....)”
因此,将函数 sum(dbinom...) 应用于 x 的每个值并返回一个列表。
基本上,它会为您完成循环。并且通常比 for 循环(在 R 中)快几倍。
如果您需要 atmost2 不是列表而是向量,您可以:
unlist(atmost2)
> unlist(atmost2)
[1] 0.9998862 0.9884964 0.9298092 0.6777995 0.5255928
根据Rui的提醒编辑
使用 sapply,其他一切都一样,但输出确实是一个向量。
x <- c(.01, .05, .10, .20, .25)
atmost2 <- as.numeric(1:length(x))
atmost2 <- sapply(x, function(x) sum(dbinom( 0:2 , size = 10, prob = x)))
atmost2 # this is a vector