Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Averages per time-steps

I am working with 24-hour time-use data. A time-step has a 1 if the measurement was taken and 0 otherwise. I want to calculate the average measurement counts over time. Based on the below example his means first I need to sum per column and multiply by time-step such as: t1 x (1+0+1) + t2 X (0+1+0) + t3 x (1+1+1) and second to divide with the sum of counts ((1+0+1)+(0+1+0)+(1+1+1)). With regards to the time-steps t1=1, t2=2 and t3=3.Therefore [(1 x 2) + (2 x 1) + (3 x 3)] / (2+1+3) = 13 / 6 = 2.16. How can I implement this for n timesteps?

Example:

id   t1 t2 t3
 10   1  0  1
 12   0  1  1
 14   1  0  1

Output: AvgC=2.16

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Sample data:

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))

>Solution :

Another solution with Base R using a self-written function:

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading