Sam Hoppen
Sam Hoppen

Reputation: 365

How can I group the same value across multiple columns and sum subsequent values?

I have a table of information that looks like the following:

  rusher_full_name  receiver_full_name rushing_fpts receiving_fpts
  <chr>             <chr>                     <dbl>          <dbl>
1 Aaron Jones       NA                          5              0  
2 NA                Aaron Jones                 0              5
3 Mike Davis        NA                          0.5            0
4 NA                Allen Robinson              0              3  
5 Mike Davis        NA                          0.7            0

What I'm trying to do is get all of the values from the rushing_fpts and receiving_fpts to sum up depending on the rusher_full_name and receiver_full_name value. For example, for every instance of "Aaron Jones" (whether it's in rusher_full_name or receiver_full_name) sum up the values of rushing_fpts and receiving_fpts

In the end, this is what I'd like it to look like:

  player_full_name    total_fpts
  <chr>                    <dbl>
1 Aaron Jones                 10  
2 Mike Davis                 1.2
3 Allen Robinson               3  

I'm pretty new to using R and have Googled a number of things but can't find any solution. Any suggestions on how to accomplish this?

Upvotes: 0

Views: 26

Answers (1)

Ben
Ben

Reputation: 30494

library(tidyverse)

df %>%
  mutate(player_full_name = coalesce(rusher_full_name, receiver_full_name)) %>%
  group_by(player_full_name) %>%
  summarise(total_fpts = sum(rushing_fpts+receiving_fpts))

Output

# A tibble: 3 x 2
  player_full_name total_fpts
  <chr>                 <dbl>
1 Aaron Jones            10  
2 Allen Robinson          3  
3 Mike Davis              1.2

Data

df <- data.frame(
  rusher_full_name = c("Aaron Jones", NA, "Mike Davis", NA, "Mike Davis"),
  receiver_full_name = c(NA, "Aaron Jones", NA, "Allen Robinson", NA),
  rushing_fpts = c(5,0,0.5,0,.7),
  receiving_fpts = c(0,5,0,3,0),
  stringsAsFactors = FALSE
)

Upvotes: 1

Related Questions