dimanche 3 décembre 2017

R Categorising data using multiple If() statements

I have created a table with football players and specific positions. I would now like to also categorise each player into their general positions (GPosition) i.e. Goalkeeper, Defender, Midfielder and Forward. Sorry if these seems rudimentary, but I am very new to R

Part of my Data is below:

            Player      Position  GPosition
1  Thibaut Courtois       Keeper  Goalkeeper
2   Willy Caballero       Keeper  Goalkeeper
9           Eduardo       Keeper  Goalkeeper
17      Matej Delac       Keeper  Goalkeeper
19       David Luiz  Centre-Back  Goalkeeper
22  Antonio Rüdiger  Centre-Back  Goalkeeper

I have tried using If() or Which() statements but have run into a few issues. When I run my code all GPositions run as GoalKeeper rather than other classifications. I am also unsure if using th "==" is the correct code to be using for this.

Part of my code:

PlayerPositions$GPosition <- if(PlayerPositions$Position == "Keeper") {
  PlayerPositions$GPosition <- "Goalkeeper"
} else if (PlayerPositions$Position == "Centre-Back"){
  PlayerPositions$GPosition <- "Defender"
} else if (PlayerPositions$Position == "Left-Back"){
  PlayerPositions$GPosition <- "Defender"
} else if (PlayerPositions$Position == "Right-Back"){
  PlayerPositions$GPosition <- "Defender"

And so on.... until last line:

} else if (PlayerPositions$Position == "Right Wing") {
  PlayerPositions$GPosition <- "Forward"
}

Aucun commentaire:

Enregistrer un commentaire