How to aggregate data in data.frame in R

Viewed 14315

I have a large data.frame. The data.frame include a lot of values.

For example:

df <- data.frame(Company = c('A', 'A', 'B', 'C', 'A', 'B', 'B', 'C', 'C'), 
                 Name = c("Wayne", "Duane", "William", "Rafael", "John", "Eric", "James", "Pablo", "Tammy"), 
                 Age = c(26, 27, 28, 32, 28, 24, 34, 30, 25), 
                 Wages = c(50000, 70000, 70000, 60000, 50000, 70000, 65000, 50000, 50000), 
                 Education.University = c(1, 1, 1, 0, 0, 1, 1, 0, 1), 
                 Productivity = c(100, 120, 120, 95, 88, 115, 100, 90, 120))

How can I aggregate my data.frame? I want to analyze values on every Company. It must look like:

enter image description here

Age -> average Age of all employees in Company

Wages -> average Wages of all employees in Company

Education.University -> sum of factors (1 or 0) for all employees in Company

Productivity -> average Productivity of all employees in Company

5 Answers

Just use the "aggregate" function

aggregate(x = df[c("Age","Wages","Education.University","Productivity")], by = df[c("Company")], FUN = mean)

#  Company      Age    Wages Education.University Productivity
#1       A 27.00000 56666.67            0.6666667     102.6667
#2       B 28.66667 68333.33            1.0000000     111.6667
#3       C 29.00000 53333.33            0.3333333     101.6667
Related