-4

Right now I have a data frame from games day (titled: games_day) that looks like this

games day

I'd like to create a new variable in the data frame summing the total points for and against each team so it will look like this

games day

so far I have used this code in dplyr games_day %>% group_by(team_id) %>% summarize(total_points_for = sum(points_for))

this does not add it into the data frame as a new variable though. Any help with this would be greatly appreciated

  • 2
    Replace `summarize()` with `mutate()` – Darren Tsai Aug 03 '20 at 12:05
  • Hi b1lly_the_kid! Welcome to Stack Overflow! Please review the following and update your post accordingly: [How to make a great R reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Eric Aug 03 '20 at 13:54

2 Answers2

1

Try this:

library(tidyverse)
#Data
df <- structure(list(team_id = c("Red", "Blue", "Yellow", "Red", "Blue", 
"Yellow"), date = c("18/01/20", "18/01/20", "19/01/20", "19/01/20", 
"20/01/20", "20/01/20"), points_for = c(16L, 12L, 10L, 9L, 17L, 
13L), points_against = c(12L, 16L, 9L, 10L, 13L, 17L)), class = "data.frame", row.names = c(NA, 
-6L))

#Code
df %>% group_by(team_id) %>% mutate(total_points_for=sum(points_for,na.rm=T),
                                    total_points_against=sum(points_against,na.rm=T))

# A tibble: 6 x 6
# Groups:   team_id [3]
  team_id date     points_for points_against total_points_for total_points_against
  <chr>   <chr>         <int>          <int>            <int>                <int>
1 Red     18/01/20         16             12               25                   22
2 Blue    18/01/20         12             16               29                   29
3 Yellow  19/01/20         10              9               23                   26
4 Red     19/01/20          9             10               25                   22
5 Blue    20/01/20         17             13               29                   29
6 Yellow  20/01/20         13             17               23                   26
Duck
  • 39,058
  • 13
  • 42
  • 84
0

A base R option using transform + ave

transform(df,
  total_points_for = ave(points_for, team_id, FUN = sum),
  total_points_against = ave(points_against, team_id, FUN = sum)
)
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81