這是我的代碼:
correlation <- function(dtable){
# create the column
dtable[, "correlation"] <- ""
for (row in 1:nrow(dtable)) {
#get the correlation for each row
cor = cor(dtable$wells_per_section[1:row], dtable$section_eur[1:row])
#store the value to the correlation column
correlation = cor
}
}
當我嘗試使用我的表時,它回傳 NA,列中沒有添加任何內容,我錯過了什么?
uj5u.com熱心網友回復:
您的函式沒有將函式的結果分配給cor()列correlation,也沒有顯式回傳dtable. 也許您可以重寫它,并進行一些更改,如下所示:
correlation <- function(dtable){
# create the column
dtable[, "correlation"] <- NA
for (row in 1:nrow(dtable)) {
#get the correlation for each row
dtable[row,"correlation"] <- cor(dtable$wells_per_section[1:row], dtable$section_eur[1:row])
}
return(dtable)
}
如果有興趣,您可以像這樣實作:
dtable["correlation"] = sapply(1:nrow(dtable),\(i) cor(dtable[1:i,1], dtable[1:i,2]))
更新
OP 現在希望按 16 行組分別進行關聯。
我認為解決這個問題的方法是使用sort(rep(..., length.out=..))如下方式創建一個分組變數,然后通過該組應用一個簡單的函式..
f <- function(w,s) {
sapply(seq_along(w), \(i) cor(w[1:i],s[1:i]))
}
dtable %>%
group_by(grp = sort(rep(1:16, length.out=250))) %>%
mutate(correlation = f(wells_per_section,section_eur))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/488550.html
