我正在處理 24 小時時間使用資料。如果進行了測量,則時間步長為 1,否則為 0。我想計算一段時間內的平均測量計數。基于下面的例子,他的意思是首先我需要對每列求和并乘以時間步長,例如:t1 x (1 0 1) t2 X (0 1 0) t3 x (1 1 1)然后除以計數的總和((1 0 1) (0 1 0) (1 1 1))。關于時間步驟t1=1, t2=2 and t3=3。因此[(1 x 2) (2 x 1) (3 x 3)] / (2 1 3) = 13 / 6 = 2.16。我如何為n時間步長實作這個?
例子:
id t1 t2 t3
10 1 0 1
12 0 1 1
14 1 0 1
輸出: AvgC=2.16
樣本資料:
df<-structure(list(id = c("10", "12", "14"), t1 = c(1, 0, 1), t2 = c(0,
1, 0), t3 = c(1, 1, 1)), class = "data.frame", row.names = c(NA,
-3L))
uj5u.com熱心網友回復:
另一種使用自寫函式的 Base R 解決方案:
calcAverage <- function(df, dt){
vector4df <- 1:(ncol(df)-1)*dt
nom <- sum(as.matrix(df[,(2:ncol(df))]) %*% vector4df)
denom <- sum(as.matrix(df[,(2:ncol(df))]))
return(nom/denom)
}
calcAverage(df, 1)
2.166667
我添加了定義 dt 的選項,這意味著“測量之間的等距時間步長”。因此,當 dt=1 時,每小時進行一次測量,當 dt =2 時,每隔一小時進行一次測量 (2,4,6,...)。
uj5u.com熱心網友回復:
與Base R,
time_step = c(1,2,3) # or 1:3
sum(time_step * colSums(df[,-1])) / sum(df[,-1])
# 2.166667
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/383800.html
