Search code examples
raggregatetally

R, how to tally by two columns?


My data looks like so,

    X  Y Goal
    32 12 1
    13 42 0
    55 33 0
    ...

I want to count how many goals in total were scored from each X-Y coordinate pairing. Any suggestions how I can do this?


Solution

  • Here's a dplyr solution.

    # Create data frame
    df <- read.table(text = "X  Y Goal
    32 12 1
    13 42 0
    55 33 0", header = TRUE)
    
    # Load library
    library(dplyr)
    
    # Group by both X & Y, then sum all goals
    df %>% 
      group_by(X, Y) %>% 
      summarise(Total = sum(Goal, na.rm = TRUE))
    #> # A tibble: 3 x 3
    #> # Groups:   X [3]
    #>       X     Y Total
    #>   <int> <int> <int>
    #> 1    13    42     0
    #> 2    32    12     1
    #> 3    55    33     0
    

    Created on 2019-03-15 by the reprex package (v0.2.1)