# [R] replacing segments of vector by their averages

jim holtman jholtman at gmail.com
Fri Jun 20 14:36:34 CEST 2008

```Does this give you the results you are expecting:

> m <- c(0.3,0.3,0.3,0.1,0.1,0.5,0.5,0.5,0.5,0.15,0.15,0.3,0.5,0.8)
> m > 0.2
  TRUE  TRUE  TRUE FALSE FALSE  TRUE  TRUE  TRUE  TRUE FALSE FALSE
TRUE  TRUE  TRUE
> m.rle <- rle(m > 0.2)
> offsets <- 1 + c(0, head(cumsum(m.rle\$lengths), -1))
> # initialize the output results
> results <- numeric(length(m.rle\$values))
> results[] <- NA
>
> for (i in seq_along(m.rle\$values)){
+     if (m.rle\$values[i]){  #numbers > 0.2
+         results[i] <- mean(m[seq(offsets[i], length=m.rle\$lengths[i])])
+     }
+ }
> results
 0.3000000        NA 0.5000000        NA 0.5333333
>

On Thu, Jun 19, 2008 at 4:55 AM, Daren Tan <daren76 at hotmail.com> wrote:
>
> Given a vector of numeric of length n, I need to find segments that are >= 0.2, compute the average of individual segments, and replace the original values in each segment by their corresponding averages.
>
> For example, there are three segments that are >= 0.2, the average of 1st segment is 0.3, 2nd is 0.5, and the 3rd is 0.5333333
>
>> c(0.3,0.3,0.3,0.1,0.1,0.5,0.5,0.5,0.5,0.15,0.15,0.3,0.5,0.8)  0.30 0.30 0.30 0.10 0.10 0.50 0.50 0.50 0.50 0.15 0.15 0.30 0.50 0.80> m >= 0.2   TRUE  TRUE  TRUE FALSE FALSE  TRUE  TRUE  TRUE  TRUE FALSE FALSE  TRUE  TRUE  TRUE
>
> _________________________________________________________________
>
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> and provide commented, minimal, self-contained, reproducible code.
>

--
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?

```