-3

I have a data frame that looks like this:

data<-data.frame(y=c(1,1,2,2,3,4,5,5),x=c(5,5,10,10,5,10,5,5))

  y  x
1 1  5
2 1  5
3 2 10
4 2 30
5 3  5
6 4 10
7 5  4
8 5  8

How can a merge those rows with same value in y column and modify the x column value to the mean of them.

I would like something like this:

  y  x
1 1  5
2 2 20
3 3  5
4 4 10
7 5  6

I'm trying:

unique(data)

But it removes the values instead of doing the mean of same rows.

Jaap
  • 81,064
  • 34
  • 182
  • 193
aspire57
  • 1,496
  • 1
  • 13
  • 19
  • 1
    The actual dupe should be [this](http://stackoverflow.com/questions/21982987/mean-per-group-in-a-data-frame) I suppose. But who cares, right? No one uses Google anymore anyway. – David Arenburg Jan 04 '16 at 14:42
  • 1
    @DavidArenburg Why google when the helpful people on SO give you a tailor-made answer in no time anyway? – Henrik Jan 04 '16 at 15:57

3 Answers3

3

It is easy with dplyr. Like here:

library("dplyr")

data %>% 
    group_by(y) %>% 
    summarise(x=mean(x))
Marta
  • 3,032
  • 3
  • 17
  • 34
2

We can use aggregate

aggregate(x~y, data, mean)
akrun
  • 874,273
  • 37
  • 540
  • 662
1

User plyr.

# Create dummy data.
nel = 30
df <- data.frame(x = round(5*runif(nel)), y= round(10*runif(nel)))

# Summarise means
require(plyr)
df$x <- as.factor(df$x)
res <- ddply(df, .(x), summarise, mu=mean(y))
Joe
  • 1,455
  • 2
  • 19
  • 36