-2

I have data that includes date, user_id, steps, heart rate.

I am trying to use dplyr mutate to give me a column that will have the average heart rate per day per user_id. There are multiple recordings for heart rate throughout the day per user. (Note: I am appending a column b/c I want to keep information for other columns such as 'steps')

Code to generate data sample

df7 <- data.frame(  date=c('2016-11-01','2016-11-01','2016-11-01','2016-11-01','2016-11-02','2016-11-02','2016-11-02','2016-11-02'),
               users_user_id=c(6,6,7,7,6,6,7,7),
               steps=c(500,2000,500,2000,600,3000,600,3000),
               avg_heart_rate=c(70,80,70,80,80,90,80,90))
df7$date <- as.Date(df7$date)

Ideally it would look something like this

date        users_user_id   steps   average_heart_rate  day_avg_hr
2016-11-01  6               500     70                  75
2016-11-01  6               2000    80                  75
2016-11-01  7               500     70                  75
2016-11-01  7               2000    80                  75
2016-11-02  6               600     80                  85
2016-11-02  6               3000    90                  85
2016-11-02  7               600     80                  85
2016-11-02  7               3000    90                  85
MrFlick
  • 195,160
  • 17
  • 277
  • 295
R. Zh
  • 51
  • 6
  • 3
    did you try `df7 %>% group_by(date, users_user_id) %>% mutate(day_avg = mean(avg_heart_rate))`? – Sotos Apr 07 '17 at 14:34
  • thanks, this works, I was using `df7$avg_heart_rate` instead of just `avg_heart_rate` ...my stupid mistake – R. Zh Apr 07 '17 at 14:43

1 Answers1

0

First summarise then join the results.

new.df <- df7 %>%
  group_by(., date, users_user_id) %>%
  summarise(., day_avg_hr = mean(avg_heart_rate)) %>%
  ungroup() %>%
  left_join(df7, .)
G. Becker
  • 46
  • 3
  • The `summarize()/join()` isn't necessary. A simple `mutate()` would work fine here (as indicated in the comments and the duplicate answer) – MrFlick Apr 07 '17 at 14:50