-1

I have a dataframe

df2
       Date Var Value
1 27/9/2019   A    56
2 28/9/2019   A    50
3 1/10/2019   A    90
4 2/10/2019   B   100

I tried to include group by inside mutate. But not able to. What I need is

df1
       Date Var Value   mean
1 27/9/2019   A    56   65.3
2 28/9/2019   A    50   65.3
3 1/10/2019   A    90   65.3 
4 2/10/2019   B   100   100

I tried with below code but did not get. Actually I need this to be done under summarise only. Is there a way?

df1 <- df2 %>% mutate(mean = group_by(Var) %>% summarise(mean(Value)))
Dev P
  • 449
  • 3
  • 12
  • Hi thanks. I am aware of this code. But it returns only mean. But I need those value columns as well. you can refer my expected output – Dev P Oct 13 '19 at 08:34
  • 1
    BTW you can do `df2 %>% group_by(Var) %>% mutate(mean = mean(Value))` – A. Suliman Oct 13 '19 at 08:38

2 Answers2

0

Try this:

df2 %>% 
  group_by(Var) %>% 
  mutate(Mean = mean(Value))


Mikel
  • 46
  • 3
0

We can use ave from base R

df2$Mean <- with(df2, ave(Value, Var))
akrun
  • 874,273
  • 37
  • 540
  • 662