Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 views
in Technique[技术] by (71.8m points)

r - Getting rid of @ and Creating Home and Away Teams

I am trying to make a home and away column for this team, in a data table that looks like

   X2021        Angels
1    1-Apr     White Sox
2    2-Apr     White Sox
3    3-Apr     White Sox
4    4-Apr     White Sox
5    5-Apr        Astros
6    6-Apr        Astros
7    7-Apr              
8    8-Apr    @Blue Jays
9    9-Apr    @Blue Jays

Every time the Angels are playing. If the team contains an @ it is away, no @ it is home, and empty there is no game. I want a column of Home Team and Away Team, where if it is away (containing @) the Angels are home and the other team is away without the @. What would look like

  X2021        Angels     Home_Team   Away_Team
1    1-Apr     White Sox  Angels      White Sox
2    2-Apr     White Sox  Angels      White Sox
3    3-Apr     White Sox  Angels      White Sox
4    4-Apr     White Sox  Angels      White Sox
5    5-Apr        Astros  Angels      Astros
6    6-Apr        Astros  Angels      Astros
7    7-Apr                      
8    8-Apr    @Blue Jays  Blue Jays   Angels
9    9-Apr    @Blue Jays  Blue Jays   Angels
question from:https://stackoverflow.com/questions/66056008/getting-rid-of-and-creating-home-and-away-teams

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

JacksonDels,

Assuming your data is in an spreadsheet, here's some code that will do what you're trying to do.

# Load libraries
library(tidyverse)
library(lubridate)

# Read in data table
df <- readxl::read_xlsx("angels.xlsx")

# Create two new columns for "Home" and "Away" teams
df <- df %>% 
  mutate("Home_Team" = if_else(str_detect(string = Angels, pattern = "@"), str_remove(string = Angels, pattern = "@"), "Angels")) %>%
  mutate("Away_Team" = if_else(str_detect(string = Angels, pattern = "@"), "Angels" ,str_remove(string = Angels, pattern = "@")))

Good Luck!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...