user2543427
user2543427

Reputation: 133

Return the Sum and then Divide a Column in R

Suppose I have imported a csv data frame df that looks like:

        User    Lesson    Score
         A       1.1       6
         A       1.2       8
         A       3.1       9
         B       1.1       7
         B       3.6       9
         C       5.3       8
         C       6.3       9

I want to sum all of the scores by user, and then divide each of these "summed" scores by 5. So that I get a data frame like:

        User        Score
         A           4.6
         B           3.2
         C           3.4

How would I go about doing that?

Upvotes: 0

Views: 1203

Answers (3)

Ferdinand.kraft
Ferdinand.kraft

Reputation: 12829

I plain R you can use this:

aggregate(df$Score, by=list(User=df$User), function(x)sum(x)/5)

Upvotes: 2

Jack Ryan
Jack Ryan

Reputation: 2144

Per comments from @Justin try:

ddply(Users, .(User), summarise, sum(Score)/5) # I named your df "Users"
# User ..1
# 1    A 4.6
# 2    B 3.2
# 3    C 3.4

Upvotes: 0

Sven Hohenstein
Sven Hohenstein

Reputation: 81753

You can use aggregate:

> aggregate(Score/5 ~ User, df, sum)
  User Score
1    A   4.6
2    B   3.2
3    C   3.4

Upvotes: 3

Related Questions