Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

r - Creating new column combining info in two columns, alphabetically

I have a dataset of football teams that looks like this:

Home_team Away_team Home_score Away_score
Arsenal    Chelsea      1        3
Manchester U  Blackburn 2        9
Liverpool      Leeds    0        8
Chelsea     Arsenal     4        1

I want to group the teams involved, regardless of which teams were playing at home and away from home. For example, if Chelsea played Arsenal, regardless of whether the game was at Chelsea or at Arsenal, I would want the new column, "teams_involved", to be Arsenal - Chelsea. My guess is the way to do this is to add these teams to the new column in alphabetical order, but I'm not sure how to do that.

Desired output:

Home_team Away_team Home_score Away_score teams_involved
Arsenal    Chelsea      1        3     Arsenal - Chelsea
Manchester U  Blackburn 2        9   Blackburn - Manchester U
Liverpool      Leeds    0        8      Leeds - Liverpool 
Chelsea     Arsenal     4        1     Arsenal - Chelsea

The reason I am seeking this is so I can see the # of wins for each team against a specific team, regardless of the location of the game.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
df = read.table(text = "
Home_team Away_team Home_score Away_score
Arsenal    Chelsea      1        3
ManchesterU  Blackburn 2        9
Liverpool      Leeds    0        8
Chelsea     Arsenal     4        1
", header=T, stringsAsFactors=F)

library(dplyr)

df %>%
  rowwise() %>%      # for each row
  mutate(Teams = paste(sort(c(Home_team, Away_team)), collapse = " - ")) %>%  # sort the teams alphabetically and then combine them separating with -
  ungroup()          # forget the row grouping

# # A tibble: 4 x 5
#   Home_team   Away_team Home_score Away_score Teams                  
#   <chr>       <chr>          <int>      <int> <chr>                  
# 1 Arsenal     Chelsea            1          3 Arsenal - Chelsea      
# 2 ManchesterU Blackburn          2          9 Blackburn - ManchesterU
# 3 Liverpool   Leeds              0          8 Leeds - Liverpool      
# 4 Chelsea     Arsenal            4          1 Arsenal - Chelsea 

An alternative solution without rowwise:

# create function and vectorize it
f = function(x,y) {paste(sort(c(x, y)), collapse = " - ")}
f = Vectorize(f)

# apply function to your dataset
df %>% mutate(Teams = f(Home_team, Away_team))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...