具有ddply的连续子组

时间:2011-04-26 14:18:19

标签: r plyr

我想在每次情况发生变化时总结我的实验数据。

例如:

> df=data.frame(tos=1:9, temp=rep(c(25,50,25), each=3), response=c(3.2,3.3,3.3, 6.5, 6.5, 6.5, 3.5,3.6,3.5))
> df
    time temp response
1   1   25      3.2
2   2   25      3.3
3   3   25      3.3
4   4   50      6.5
5   5   50      6.5
6   6   50      6.5
7   7   25      3.5
8   8   25      3.6
9   9   25      3.5

我想以这种方式总结一下:

temp response.mean
25      3.3
50      6.5
25      3.5

如果像这样使用ddply:

  

库(plyr)
  ddply(df,c(“temp”),summary,reponse.mean = mean(response)

输出是:

  temp response.mean
1   25           3.4
2   50           6.5

有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:11)

以下是实现此目的的一种方法

# find how many observations in each experiment
tmp1    = rle(df$temp)$lengths

# create a column referring to experiment number
df$expt = rep(1:length(tmp1), tmp1)

# compute means for each combination of temp and expt
ddply(df, .(expt, temp), summarize, response.mean = mean(response))

这会产生输出

   expt temp response.mean
1    1   25      3.266667
2    2   50      6.500000
3    3   25      3.533333