Rad
Rad

Reputation: 1029

Aggregate a dataframe based on three columns in R

I have a dataframe with a structure like this :

    V1    V2   V3       V4     
1   1.35  A  10241297 10459084
2  16.00  A  10241297 10459084
3   1.47  A  10241297 10459084

I would like to average V1 based on V2, V3 and V4

All aggregate example I saw are dealing with aggregating based on a single value.

Any help is appreciated

Thanks

Upvotes: 3

Views: 9682

Answers (2)

Simon O'Hanlon
Simon O'Hanlon

Reputation: 59970

This is one of the ways you could accomplish what I think you are looking for (hard to tell because you have one set of unique identifiers in the example data):

aggregate( V1 ~ V2 + V3 + V4 , df , mean )
# V2       V3       V4       V1
# 1  A 10241297 10459084 6.273333

Upvotes: 11

Didzis Elferts
Didzis Elferts

Reputation: 98419

Here is a plyr approach.

library(plyr)
ddply(df,.(V2,V3,V4),summarise,V1=mean(V1))
  V2       V3       V4       V1
1  A 10241297 10459084 6.273333

Upvotes: 1

Related Questions