Create a new conditional column

I have a dataset with this structure:

df <- data.frame(
  stringsAsFactors = FALSE,
                    Home = c("Huesca",
                             "Zaragoza","Real Sociedad B","Girona","Ponferradina",
                             "Sporting Gijón","Oviedo"),
                    Away = c("Eibar","UD Ibiza",
                             "Leganés","SD Amorebieta","Alcorcón","Burgos",
                             "Lugo"),
         HomeGoals = c(2L, 0L, 1L, 2L, 1L, 1L, 2L),
         AwayGoals = c(0L, 0L, 0L, 0L, 0L, 0L, 2L),
                GD = c(2L, 0L, 1L, 2L, 1L, 1L, 0L),
                   score = c("2 - 0","0 - 0",
                             "1 - 0","2 - 0","1 - 0","1 - 0","2 - 2")
      )

I want to create a new column, called FTR, populate with one of this values: H (if HomeGoals are larger than AwayGoals) , D(if Home and away are the same) or A(if AwayGoals are larger than HomeGoals). How can I get this?

Thanks in advance.

library(tidyverse)

df <- data.frame(
  stringsAsFactors = FALSE,
  Home = c("Huesca",
           "Zaragoza","Real Sociedad B","Girona","Ponferradina",
           "Sporting Gijón","Oviedo"),
  Away = c("Eibar","UD Ibiza",
           "Leganés","SD Amorebieta","Alcorcón","Burgos",
           "Lugo"),
  HomeGoals = c(2L, 0L, 1L, 2L, 1L, 1L, 2L),
  AwayGoals = c(0L, 0L, 0L, 0L, 0L, 0L, 2L),
  GD = c(2L, 0L, 1L, 2L, 1L, 1L, 0L),
  score = c("2 - 0","0 - 0",
            "1 - 0","2 - 0","1 - 0","1 - 0","2 - 2")
)

df <- df %>% 
  mutate(FTR = case_when(
    HomeGoals > AwayGoals ~ "H",
    HomeGoals == AwayGoals ~ "D",
    HomeGoals < AwayGoals ~ "A"))

Result:

             Home          Away HomeGoals AwayGoals GD score FTR
1          Huesca         Eibar         2         0  2 2 - 0   H
2        Zaragoza      UD Ibiza         0         0  0 0 - 0   D
3 Real Sociedad B       Leganés         1         0  1 1 - 0   H
4          Girona SD Amorebieta         2         0  2 2 - 0   H
5    Ponferradina      Alcorcón         1         0  1 1 - 0   H
6  Sporting Gijón        Burgos         1         0  1 1 - 0   H
7          Oviedo          Lugo         2         2  0 2 - 2   D
> 

Great. Works perfectly. Thanks Flm.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.