Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to aggregate some columns while keeping other columns in R?

Tags:

r

aggregate

I have a data frame like this:

     id  no  age
1    1   7   23
2    1   2   23
3    2   1   25
4    2   4   25
5    3   6   23
6    3   1   23

and I hope to aggregate the date frame by id to a form like this: (just sum the no if they share the same id, but keep age there)

    id  no  age
1    1   9   23
2    2   5   25
3    3   7   23

How to achieve this using R?

like image 436
Nip Avatar asked Apr 12 '13 19:04

Nip


People also ask

Can aggregate function be used for multiple columns?

We can use the aggregate() function in R to produce summary statistics for one or more variables in a data frame.

Which function is used to aggregate values from multiple columns in to one?

The aggregate() function in R is used to produce summary statistics for one or more variables in a data frame or a data.


1 Answers

Assuming that your data frame is named df.

aggregate(no~id+age, df, sum)
#   id age no
# 1  1  23  9
# 2  3  23  7
# 3  2  25  5
like image 146
Didzis Elferts Avatar answered Sep 17 '22 13:09

Didzis Elferts