How to group data by more than two factors in R

I have a dataset that looks below. There are 8619 rows in a real dataset.

Athlete      Competing Country  Year    Total Medals
Michael Phelps    United States 2012    6
Alicia Coutts     Australia     2012    5
Missy Franklin    United States 2012    5
Brian Leetch      United States 2002    1
Mario Lemieux     Canada        2002    1
Ylva Lindberg     Sweden        2002    1
Eric Lindros      Canada        2002    1
Ulrica Lindström  Sweden        2002    1
Shelley Looney    United States 2002    1

and I want to change this data for countries, years and the amount of medals.

I need a result like

Country        Year  SumOfMedals
United States  2012  11
United States  2002   2
...

by(newmd$Total.Medals, newmd$Year, FUN=sum)
by(md$Total.Medals, md$Competing.Country, FUN=sum)

I'm tired of using the argument, but still stuck. Can any of you help me?

+4
source share
2 answers

You can do this quite easily, using aggregateto get the sum of the number of medals:

md2 <- aggregate(cbind(SumOfMedals = Total.Medals) ~ Competing.Country + Year),
          data = md,
          FUN = sum)

The next step will be sorting md2on Competing.Countryand SumOfMedals, which is done using the function order:

md2 <- md2[order(Competing.Country, -SumOfMedals),] 

Done.

+2
source

data.table, 'data.frame' 'data.table' (setDT(df1)), 'Competing_Country', 'Year', sum Total_Medals and then " .

library(data.table)
setDT(df1)[,list(SumOfMedals = sum(Total_Medals)), 
   by = .(Competing_Country, Year)
        ][order(-Competing_Country, -Year, -SumOfMedals)]

dplyr .

library(dplyr)
df1 %>%
    group_by(Competing_Country, Year) %>%
    summary(SumOfMedals = sum(Total_Medals) %>%
    arrange(desc(Competing_Country), desc(Year), desc(SumOfMedals))

 df1 <- structure(list(Athlete = c("Michael Phelps", "Alicia Coutts", 
"Missy Franklin", "Brian Leetch", "Mario Lemieux", "Ylva Lindberg", 
"Eric Lindros", "Ulrica Lindström", "Shelley Looney"), Competing_Country = c("United States", 
"Australia", "United States", "United States", "Canada", "Sweden", 
"Canada", "Sweden", "United States"), Year = c(2012L, 2012L, 
2012L, 2002L, 2002L, 2002L, 2002L, 2002L, 2002L), Total_Medals = c(6L, 
5L, 5L, 1L, 1L, 1L, 1L, 1L, 1L)), .Names = c("Athlete", "Competing_Country", 
"Year", "Total_Medals"), class = "data.frame", row.names = c(NA, 
-9L))
+3

Source: https://habr.com/ru/post/1617931/


All Articles