0

I have a data frame that looks like the following:

team playername points
team1 player1     80
team1 player2     40
...
team2 player1     98
...
team20 player1    40

It has 3 columns, the team name, player name, and the total points that player has scored. What I want to do is loop through the data frame and calculate the sum on a per team basis. So team1's total points would be 120 in the following example. I wrote some test code earlier to try to get some output:

curTeam = ""
count = 0
for (i in df) {
    if (curTeam == i$Team) {
        count = count + i$points
    } else {
        print (count)
        curTeam = i$Team
        count = i$points
    }
}

I'm getting the following error:

$ operator is invalid for atomic vectors

Is there a better way to do what I'm trying to do?

Thanks.

parksw3
  • 649
  • 4
  • 11
Alex Cauthen
  • 497
  • 5
  • 12
  • 32
  • 1
    `xtabs(points ~ team, df)` should do it. Also see `?aggregate`. – Rich Scriven Oct 17 '16 at 16:24
  • Unfortunately I don't have the luxury of programming in RStudio so I don't have access to the help functions or the ability to see the objects that were created. Does xtabs return a list? Would it be possible to throw this information into a bar char? – Alex Cauthen Oct 17 '16 at 16:29
  • 1
    You can't see the results and you have no help files? What platform are you using? – Rich Scriven Oct 17 '16 at 16:33
  • 1
    Just type `?aggregate` and a help file will pop up, one way or another. – Roman Luštrik Oct 17 '16 at 16:33

1 Answers1

0

How about this?

df <- read.table(text = "team playername points
team1 player1     80
team1 player2     40
team2 player1     98
team20 player1    40", header = TRUE)

library(tidyr)
library(dplyr)
df %>% group_by(team) %>% summarise(sum(points))
parksw3
  • 649
  • 4
  • 11