r - dplyr mutate based on two vectors (calculating a 3rd column based on grouping from 2 columns) -
this question has answer here:
- mean per group in data.frame [duplicate] 8 answers
i have data includes date, user_id, steps, heart rate.
i trying use dplyr
mutate
give me column have average heart rate per day per user_id. there multiple recordings heart rate throughout day per user. (note: appending column b/c want keep information other columns such 'steps')
code 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 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
first summarise
join
results.
new.df <- df7 %>% group_by(., date, users_user_id) %>% summarise(., day_avg_hr = mean(avg_heart_rate)) %>% ungroup() %>% left_join(df7, .)
Comments
Post a Comment