Continuous Block Averaging

I have the following data:

f  x 
A 1.1
A 2.2
A 3.3
B 3.5
B 3.7
B 3.9
B 4.1
B 4.5
A 5.1
A 5.2
C 5.4
C 5.5
C 6.1
B 6.2
B 6.3

I would like to average xover continuous blocks fto get this, similarly tapply(...,mean), but realizing the fact that he should not mix individual blocks in the original order:

f  x
A 2.2
B 3.94
A 5.15 
C 5.67
B 6.25
+5
source share
2 answers

rle - one of the possibilities:

> id <- rle(as.character(Data$f))
> Means <-tapply(Data$x,rep(1:length(id$lengths),id$lengths),mean)    
> data.frame(Means,f=id$values)
     Means f
1 2.200000 A
2 3.940000 B
3 5.150000 A
4 5.666667 C
5 6.250000 B

It gives you runs and values, so you can use both.

+5
source

Here is one way:

## reproducible code for example
dat <- read.table(foo <- textConnection("f  x 
A 1.1
A 2.2
A 3.3
B 3.5
B 3.7
B 3.9
B 4.1
B 4.5
A 5.1
A 5.2
C 5.4
C 5.5
C 6.1
B 6.2
B 6.3
"), header = TRUE)
close(foo)

We use rle()to calculate the length of the run fand create a new factor facthat indexes changes, if it does not want a better word, c f. Then we summarize on fand fac:

lens <- with(dat, rle(as.character(f)))
dat$fac <- with(lens, factor(rep(seq_along(lengths), times = lengths)))
aggregate(x ~ f + fac, data = dat, FUN = mean)

Donation:

> aggregate(x ~ f + fac, data = dat, FUN = mean)
  f fac        x
1 A   1 2.200000
2 B   2 3.940000
3 A   3 5.150000
4 C   4 5.666667
5 B   5 6.250000

We can easily discard the second column facas a result if this is undesirable:

> aggregate(x ~ f + fac, data = dat, FUN = mean)[,-2]
  f        x
1 A 2.200000
2 B 3.940000
3 A 5.150000
4 C 5.666667
5 B 6.250000
+6
source

All Articles