Mean by line range

Asked

Viewed 42 times

1

I’m working on the R with only 1 column, it has 3651 lines and need to make several averages along the column.

I need the average every 5 lines. I am working with atmospheric pressure data. and they are divided into 1 in 1 minute. I need the average of 5 to work with another table where the data are 5 by 5.

set.seed(7863)
n <- 3651
  • 1

    The average of 5 in 5 notes is X_1 to X_5, X_2 to X_6, X_3 to X_7 and so on or X_1 to X_5, X_6 to X_10, X_11 to X_15 and so on?

  • That would be: X_1 to X_5, X_6 to X_10, X_11 to X_15 and so on...

  • Can you please, edit the question with the departure of dput(head(dados, 20))? It is that if they are given in it enters a variable time (in minutes) the answer I gave can change a lot. Note: dados is the base name, for example a data frame..

1 answer

1

The following function calculates averages

  1. tipo = "segmentos" m. In the case of the question m = 5, that is, the averages of elements 1-5 are calculated, after 6-10, 11-15, etc.
  2. tipo = "movel". The averages of the elements 1-5 are calculated, after 2-6, 3-7, etc. This type of averages uses the package zoo.

The example tests the function with a vector, not with a dataframe column.

mediaKamila <- function(x, m = 5, tipo = "segmentos", na.rm = TRUE, ...){
  n <- length(x)
  if(tipo == "movel"){
    zoo::rollmeanr(x, k = m, ...)
  }else{
    f <- c(1L, rep(0, m - 1))
    f <- cumsum(rep(f, ceiling(n / m), length.out = n))
    ave(x, f, FUN = mean, na.rm = na.rm)
  }
}

y <- 1:31
mediaKamila(y)
mediaKamila(y, tipo = "movel")
zoo::rollmeanr(1:31, 5)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.