r - How to get the average (or sum, count, etc.) of variables for each group ID? -


i have data frame list of ids , other variables so:

student_id       score 6                94 2                63 6                100 7                44 6                97 2                67 

i create data frame consists of student_id , average score this:

student_id       avg_score 2                65 6                97 7                44  

the actual data set larger, of course.

you can use dplyr package:

df %>% group_by(student_id) %>% summarise(avg_score = mean(score))   # # tibble: 3 x 2  #   student_id avg_score  #        <int>     <dbl>  # 1          2        65  # 2          6        97  # 3          7        44 

you can use aggregate in base r:

aggregate( score ~ student_id, df, mean) #column name remain "score"  #   student_id score  # 1          2    65  # 2          6    97  # 3          7    44 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -