我需要一些幫助來回圈我的代碼或為我需要的計算創建一個函式。
我的資料框如下。除了 newdat2$time 之外,所有列在每一行中都重復相同的值,每一行的值都會改變:
newdat2 <- data.frame(season = rep("Summer", 31),
time = seq(0, 3, by = 0.1),
temp = rep(21.79384, 31),
last.rain.bom = rep(4.232604, 31),
rain = rep(0.916501, 31),
wind = rep("nil", 31),
cloud = rep(40.20378, 31),
abundance = rep(117.6262, 31),
site = rep("Avalon", 31))
對于這個資料框的每一行,我想完成下面的計算。此計算是計算擬合模型預測的標準誤差,請參見此處。
C = c(0,0,0,0,0,0,0.0,0,0,0,0,0,0, 0, 1,0,0,0,time,21.8,4.23,0.917,0,0,0,40.2,4.78) # This represents covariate values of my fitted model. The value of time needs to change for each row of newdat2$time, all other values remain the same
s <- vcov(zib) # zib is my fitted model and this row of code is taking the variance covariance matrix of my fitted model. s is a matrix 27x27
newdat2$se <- sqrt(t(C) %*% s %*% C) # This then calculates the standard errors for my model predictions but C must change for each row of newdat2 to reflect the change in newdat2$time
例如,回圈/函式完成的第一個計算將是
C = c(0,0,0,0,0,0,0.0,0,0,0,0,0,0, 0, 1,0,0,0,0,21.8,4.23,0.917,0,0,0,40.2,4.78) # 0 is the first value of newdat2$time
s <- vcov(zib)
newdat2$se <- sqrt(t(C) %*% s %*% C)
回圈/函式完成的第二個計算將是
C = c(0,0,0,0,0,0,0.0,0,0,0,0,0,0, 0, 1,0,0,0,0.1,21.8,4.23,0.917,0,0,0,40.2,4.78) # 0.1 is the second value of newdat2$time
s <- vcov(zib)
newdat2$se <- sqrt(t(C) %*% s %*% C)
回圈/函式完成的第三次計算將是
C = c(0,0,0,0,0,0,0.0,0,0,0,0,0,0, 0, 1,0,0,0,0.2,21.8,4.23,0.917,0,0,0,40.2,4.78) # 0.2 is the third value of newdat2$time
s <- vcov(zib)
newdat2$se <- sqrt(t(C) %*% s %*% C)
任何幫助回圈這樣的計算或創建一個函式來實作這一點將非常感激。
uj5u.com熱心網友回復:
我這里沒有資料或預期的結果,但這應該可行:
這個想法是將向量的所有版本C變成一個矩陣,然后用它進行計算。你只需要結果答案的對角線元素,所以我認為colSums(m * s %*% m)會給出相同的答案,但速度更快。
C = c(0,0,0,0,0,0,0.0,0,0,0,0,0,0, 0, 1,0,0,0,0,21.8,4.23,0.917,0,0,0,40.2,4.78)
m <- matrix(rep(C, length(newdat2$time)), ncol = length(newdat2$time))
m[19, ] <- newdat2$time
s <- vcov(zib)
newdat2$se <- sqrt(colSums(m * s %*% m))
這應該比回圈更快。
uj5u.com熱心網友回復:
通過回圈,你可以像下面這樣:
newdat<-NULL
for(i in 1:length(newdat2$time))
{
C = c(0,0,0,0,0,0,0.0,0,0,0,0,0,0, 0, 1,0,0,0,newdat2$time[i],21.8,4.23,0.917,0,0,0,40.2,4.78)
s <- vcov(zib)
newdat<-c(newdat,sqrt(t(C) %*% s %*% C))
}
現在您可以將newdat向量添加到資料幀中。但是,我同意上面@Brian 的觀點,即與他建議的矢量化方法相比,此方法速度較慢。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/356513.html
上一篇:基于其他列R的因素重命名級別
下一篇:R-遍歷2個串列并回傳一個串列
