| Hometeam | Awayteam | FTR |
|---|---|---|
| liverpool | unicorn | H |
| west ham. | jibb. | D. |
| Man City. | joker. | A. |
| Bournemouth. | house. | H. |
| Sheffield. | superman. | A. |
How do I replace H with data from Hometeam, A with Awayteam, and D with the word Draw all in one shot?
I tried using str_replace but it only works with one specific data.... Help pls
CodePudding user response:
One way is to use case_when inside of mutate.
library(tidyverse)
df %>%
mutate(FTR = case_when(FTR == "H" ~ HomeTeam,
FTR == "A" ~ AwayTeam,
FTR == "D" ~ "Draw"))
Output
HomeTeam AwayTeam FTR
1 Liverpool Norwich Liverpool
2 West Ham Man City Man City
3 Bournemouth Sheffield United Draw
Or if you want to stick to str_replace, then you can also use it inside of case_when.
df %>%
mutate(FTR = case_when(
str_detect(FTR, "H") ~ HomeTeam,
str_detect(FTR, "A") ~ AwayTeam,
str_detect(FTR, "D") ~ "Draw"
))
Data
df <-
structure(
list(
HomeTeam = c("Liverpool", "West Ham", "Bournemouth"),
AwayTeam = c("Norwich", "Man City", "Sheffield United"),
FTR = c("H",
"A", "D")
),
class = "data.frame",
row.names = c(NA,-3L)
)
