Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

I would not use a for loop in this case, since it is utterly unnecessary.

Here is a tidyverse approach. Based on your desired output, each Date would still have two records after the mean is calculated. If you only want a single row for each Date, use summarise() instead of mutate().

mutate()

library(tidyverse)

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

# A tibble: 4 x 3
# Groups:   Date [2]
   Temp Date       mean_Temp
  <dbl> <chr>          <dbl>
1     4 2018-01-01       3.5
2     3 2018-01-01       3.5
3     2 2018-01-02       2  
4     2 2018-01-02       2  

summarise()

df %>% group_by(Date) %>% summarize(mean_Temp = mean(Temp))

# A tibble: 2 x 2
  Date       mean_Temp
  <chr>          <dbl>
1 2018-01-01       3.5
2 2018-01-02       2  
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading