Home > OS >  rollmean fill NAs with original value
rollmean fill NAs with original value

Time:09-23

I followed this example to do a rolling mean rollmin in R similar to zoo package rollmax

But the first few are filled with NA's. How can I fill the NA's with the original value so that I don't lose datapoints?

CodePudding user response:

We may use coalesce with the original vector to replace the NA with that corresponding non-NA element from original vector

library(dplyr)
library(zoo)
coalesce(rollmeanr(x, 3, fill = NA), x)

If it is a data.frame

ctd %>%
    group_by(station) %>%
    mutate(roll_mean_beam = coalesce(rollmeanr(beam_coef, 
         k = 5, fill = NA), beam_coef))

data

x <- 1:10

CodePudding user response:

1) Using the original values seems a bit bizarre. Taking the rolling minimum of 1:10 using a width of 3 would give

1 2 1 2 3 4 5 6 7 8

I think what you really want is to apply min to however many points are available so that in this example we get

1 1 1 2 3 4 5 6 7 8

Now rollapplyr with partial=TRUE will use whatever number of points are available if fewer than width=3 exist at that point. At the first point only one point is available so it returns min(x[1]). At the second only two points are available so it returns min(x[1:2]). For all the rest it can use three points. Only zoo is used.

library(zoo)

x <- 1:10
rollapplyr(x, 3, min, partial = TRUE)
## [1] 1 1 1 2 3 4 5 6 7 8

2) The above seems more logical than filling the first two points with the first two input values but if you really wanted to do that anyways then simply prefix the series with the original values using c or use one of the other alternatives shown below. Only zoo is used.

c(x[1:2], rollapplyr(x, 3, min))
## [1] 1 2 1 2 3 4 5 6 7 8

pmin(rollapplyr(x, 3, min, fill = max(x)), x)
## [1] 1 2 1 2 3 4 5 6 7 8

replace(rollapplyr(x, 3, min, fill = NA), 1:2, x[1:2])
## [1] 1 2 1 2 3 4 5 6 7 8

Min <- function(x) if (length(x) < 3) tail(x, 1) else min(x)
rollapplyr(x, 3, Min, partial = TRUE)
## [1] 1 2 1 2 3 4 5 6 7 8
  •  Tags:  
  • r
  • Related