0

Suppose I have a data.frame, df.

a b d
1 2 4
1 2 5
1 2 6
2 1 5
2 3 6
2 1 1

I'd like to operate on it so that for all places where a and b are equal, I compute the mean of d.

I found that using aggregate can do this, aggregate(d ~ a + b, df, mean) This gives me something reasonable

a b d
1 2 5
2 1 3
2 3 6

But I would ideally like to keep my original d column, and add a new column m, so that I get the original data.frame with a new column "m" that contains the averages like,

a b d m
1 2 4 5
1 2 5 5
1 2 6 5
2 1 5 3
2 3 6 6
2 1 1 3

Any ideas on how to do this "properly" in R?

phil652
  • 1,484
  • 1
  • 23
  • 48
Mark
  • 45
  • 6

1 Answers1

1
library(dplyr)

df <- read.table(text = "a b d
1 2 4
1 2 5
1 2 6
2 1 5
2 3 6
2 1 1
" , header = T)


df %>% 
  group_by(a , b)  %>%
  mutate(m = mean(d))
Nader Hisham
  • 5,214
  • 4
  • 19
  • 35