'Creating new column in R based on different column with a for loop

I try to create a new column in R, which contains the mean of values of a different column but for their respective date.

My data frame looks something like this:

Temp  Date
4    2018-01-01
3    2018-01-01
2    2018-01-02
2    2018-01-02

I now want to create a third column, with the mean temperature for each day. So that it looks like this:

Temp  Date       mean_Temp
4    2018-01-01   3.5
3    2018-01-01   3.5
2    2018-01-02    2
2    2018-01-02    2

I already tried:

 for (i in as.list(df$Date)) {
   df$mean_Temp[i] <- paste(mean(df$Temp))
}

But that doesn't work, it only returns the overall mean of the temperature and doesn't calculate the mean for every day individually. Thank you guys, I hope I made my problem clear.



Solution 1:[1]

Try:

library(dplyr)
df %>% group_by(Date) %>% mutate(mean_Temp = mean(Temp))

When grouping with dplyr, you can either use summarise or mutate. summarise will return one row per group while mutate will add/modify one column and repeat the value for all the entries in each group.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Javier Herrero