df <- c(2,4,1,5,9,5,7,5,9,8,7,5,6,8,4,2,8,1,9,3,8,5,11,16,10)
I need to get the average of the df in ascending order with 20% observation each. means separate average of 5 observation in ascending or descending order.
Thanks in advance
df <- c(2,4,1,5,9,5,7,5,9,8,7,5,6,8,4,2,8,1,9,3,8,5,11,16,10)
I need to get the average of the df in ascending order with 20% observation each. means separate average of 5 observation in ascending or descending order.
Thanks in advance
suppressPackageStartupMessages({
library(zoo)
})
dat <- c(2,4,1,5,9,5,7,5,9,8,7,5,6,8,4,2,8,1,9,3,8,5,11,16,10)
rollmean(dat,5)
#> [1] 4.2 4.8 5.4 6.2 7.0 6.8 7.2 6.8 7.0 6.8 6.0 5.0 5.6 4.6 4.8
#> [16] 4.6 5.8 5.2 7.2 8.6 10.0
Another option that I learned today from SO:
> dat <- c(2, 4, 1, 5, 9, 5, 7, 5, 9, 8, 7, 5, 6, 8, 4, 2, 8, 1, 9, 3, 8, 5, 11, 16, 10)
> as.numeric(x = stats::filter(x = dat, rep(x = (1 / 5), each = 5), sides = 2))
[1] NA NA 4.2 4.8 5.4 6.2 7.0 6.8 7.2 6.8 7.0 6.8 6.0 5.0 5.6 4.6 4.8
[18] 4.6 5.8 5.2 7.2 8.6 10.0 NA NA
If you've used the purrr package and enjoy its API, you might like slider
library(slider)
library(tibble)
df <- tibble(
x = c(2,4,1,5,9,5,7,5,9,8,7,5,6,8,4,2,8,1,9,3,8,5,11,16,10),
# Current value + 4 before it
mean = slide_mean(x, before = 4, complete = TRUE)
)
df
#> # A tibble: 25 x 2
#> x mean
#> <dbl> <dbl>
#> 1 2 NA
#> 2 4 NA
#> 3 1 NA
#> 4 5 NA
#> 5 9 4.2
#> 6 5 4.8
#> 7 7 5.4
#> 8 5 6.2
#> 9 9 7
#> 10 8 6.8
#> # … with 15 more rows
Created on 2021-05-06 by the reprex package (v1.0.0)
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.
If you have a query related to it or one of the replies, start a new topic and refer back with a link.