Here is my attempt. You can use group_by() and get combinations of id , target and trial . For each combination, you want to get the average for bin0-bin3. In this case, you can do summarise_each() .
mydf <- data.frame(id = c(1,1,1,1,1,1,1,1,2,2,2,2), target = c("target", "target", "target", "target", "distractor", "distractor", "distractor", "distractor", "target", "target", "distractor", "distractor"), trial = c("2c", "2c", "2e", "2e", "2c", "2c", "2e", "2e", "2c", "2c", "2e", "2e"), bin0 = c(3,2,0,0,0,0,0,0,1,2,0,0), bin1 = c(0,0,1,0,3,0,0,0,1,0,0,0), bin2 = c(2,3,1,0,0,0,1,0,0,0,0,0), bin3 = c(0,0,2,0,1,0,0,3,1,2,0,0), stringsAsFactors = FALSE) library(dplyr) group_by(mydf, id, target, trial) %>% summarise_each(funs(mean(., na.rm = TRUE)), bin0:bin3) # id target trial bin0 bin1 bin2 bin3 #1 1 distractor 2c 0.0 1.5 0.0 0.5 #2 1 distractor 2e 0.0 0.0 0.5 1.5 #3 1 target 2c 2.5 0.0 2.5 0.0 #4 1 target 2e 0.0 0.5 0.5 1.0 #5 2 distractor 2e 0.0 0.0 0.0 0.0 #6 2 target 2c 1.5 0.5 0.0 1.5
Alternatively, you can try the data.table package data.table perform the same operation.
foo <- setDT(mydf)[, lapply(.SD, mean), by = list(id, target, trial)] print(foo) # id target trial bin0 bin1 bin2 bin3 #1: 1 target 2c 2.5 0.0 2.5 0.0 #2: 1 target 2e 0.0 0.5 0.5 1.0 #3: 1 distractor 2c 0.0 1.5 0.0 0.5 #4: 1 distractor 2e 0.0 0.0 0.5 1.5 #5: 2 target 2c 1.5 0.5 0.0 1.5 #6: 2 distractor 2e 0.0 0.0 0.0 0.0