Alternative solutions using data.table and plyr :
1) Using data.table
require(data.table) dt <- data.table(dat, key="group") # Following @Matthew comment, edited: dt[, `:=`(m_x = mean(x), m_y = mean(y)), by=group]
Output:
group xy m_x m_y 1: 1 1 2 3 4 2: 1 3 4 3 4 3: 1 5 6 3 4 4: 2 7 8 9 10 5: 2 9 10 9 10 6: 2 11 12 9 10
2) using plyr and convert:
require(plyr) ddply(dat, .(group), transform, m_x=mean(x), m_y=mean(y))
output:
group xy m_x m_y 1 1 1 2 3 4 2 1 3 4 3 4 3 1 5 6 3 4 4 2 7 8 9 10 5 2 9 10 9 10 6 2 11 12 9 10
3) using plyr and numcolwise (note the reduced output):
ddply(dat, .(group), numcolwise(mean))
Output:
group xy 1 1 3 4 2 2 9 10
source share