Q: Aggregating lines in a data frame I have a data.frame of this format:
df <- data.frame(time = seq(0.2,4,0.2), behavior = c(rep(0,4),rep(1,4),rep(2,4),rep(0,4),rep(1,4)), n1 = rnorm(20), n2 = rnorm(20))

So each row in df is a time point (the actual time is indicated by df$time), and df$behavior indicates the behavior observed in the conducted experiment at that time point.
I'd like to aggregate the data.frame according to identical consecutive df$behavior values (i.e., the same observed behavior). df$time should be summed and the resulting df$n1, df$n2,... columns should be averaged over the sum of df$time.
So for this example the result would be:
> agg.df
  time behavior          n1          n2
1  2.0        0 -1.19640776 -1.78875416
2  5.2        1 -0.52219794  0.15352409
3  8.4        2  0.40486487 -0.12017916
4 11.6        0  0.15282416 -0.08090696
5 14.8        1  0.05377323 -0.01250031

What's the most efficient way to achieve this?

A: Here is one way using dplyr. Since you use rnorm without set.seed in your df, my result is not identical to yours.
df %>%
    group_by(group = cumsum(c(T, diff(behavior) != 0))) %>% # assigning groups
    summarise(Time = sum(time),
              ave.n1 = sum(n1) / Time,
              ave.n2 = sum(n2) / Time)


# group Time      ave.n1      ave.n2
#1    1  2.0  0.68164245 -1.57266432
#2    2  5.2 -0.26419520  0.19598772
#3    3  8.4 -0.04105184  0.24406783
#4    4 11.6  0.10536325 -0.28962844
#5    5 14.8 -0.09449933 -0.02142792

If you have n1-n200, you could do something like this. Please note that your n1-n200 are
overwritten here. You could do mutate_each(funs(./time), vars = matches("^n")). This will
create 200 columns with column names like var1, var2. You need to replace the names by yourself.
This renaming part is a bit pain with the current version of dplyr. But you can easily do
this using gsub, for instance.
df %>%
    group_by(group = cumsum(c(T, diff(behavior) != 0))) %>%
    summarise_each(funs(sum = sum(., na.rm = TRUE))) %>%
    mutate_each(funs(./time), matches("^n")) %>%
    select(-behavior)

If you want to keep the original behaviour you could do something like this.
df %>%
    group_by(group = cumsum(c(T, diff(behavior) != 0))) %>%
    summarise(behavior = behavior[1]) -> foo;
    df %>%
    group_by(group = cumsum(c(T, diff(behavior) != 0))) %>%
    summarise(Time = sum(time),
              ave.n1 = sum(n1) / Time,
              ave.n2 = sum(n2) / Time) %>%
    do(cbind(.,foo[,2]))

# group Time      ave.n1      ave.n2 behavior
#1    1  2.0  0.93849292  0.90373785        0
#2    2  5.2  0.26211881 -0.11678684        1
#3    3  8.4  0.12171471  0.15838066        2
#4    4 11.6  0.11046081  0.17450358        0
#5    5 14.8 -0.06480093  0.03401513        1

