这是一种方法:
## 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)
我们使用rle() 来计算f 的运行长度,并创建一个新因子fac 来索引f 中的更改,以便找到更好的词。然后我们在 f 和 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)
给予:
> 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
如果不希望这样做,我们可以轻松地删除结果中的第二列 fac:
> 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