我有一個像這樣的資料框
ourmodel difference new_topic
1 2 0.08233167 1
2 3 0.07837389 2
3 1 0.15904427 3
4 3 0.05716799 4
5 1 0.13388058 3
6 3 0.09156650 3
我希望將模型的每個輸出保存在變數中out。我的方法似乎不起作用 - 誰能看到我做錯了什么?我是這樣做的:
library(rethinking)
out <- list()
for (i in unique(singo$new_topic)) {
i <- ulam(
alist(
difference ~ dnorm(mu, sigma),
mu <- a[ourmodel],
a[ourmodel] ~ dnorm(0.40, 0.15) ,
sigma ~ dexp(2)
), data = final, chains = 4, cores = 4)
out[[i]] <- precis(i, depth = 2)
}
我收到以下錯誤
Error in out[[i]] <- precis(i, depth = 2) : invalid subscript type 'S4'
uj5u.com熱心網友回復:
你犯了兩個錯誤:
1. 您正在遍歷 S4 物件,而不是整數。
而不是
for (i in unique(singo$new_topic))
你要
max_i <- length(unique(singo$new_topic))
for (i in 1:max_i)
您得到的錯誤是因為您正在迭代 的元素singo并嘗試使用它們而不是整數進行子集化。
此示例可能使錯誤的性質更清楚:
animals <- c("cow", "pig", "sheep")
## This works
for(i in 1:length(animals)){
print(animals[[i]])
}
#> [1] "cow"
#> [1] "pig"
#> [1] "sheep"
## This also works
for(i in animals){
print(i)
}
#> [1] "cow"
#> [1] "pig"
#> [1] "sheep"
## This does not
for(i in animals){
print(animals[[i]])
}
#> Error in animals[[i]]: subscript out of bounds
創建于 2022-11-18,使用reprex v2.0.2
2.你正在覆寫i
如果您想對i串列進行子集化,則不應覆寫i串列第一行中的值。所以做這樣的事情:
for(i in 1:max_i){
## don't assign to i here:
j <- ulam(
## some code
)
## Use i as the index, j as the first argument to precis()
out[[i]] <- precis(j, depth = 2)
}
3. 獎勵:最好制作一個正確長度的空串列。
所以嘗試:
out <- vector("list", length = max_i)
out在運行 for 回圈之前進行初始化。這使您的代碼更清晰,運行速度更快。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/537554.html
標籤:r循环
