Reputation: 8454
I have the dataframe below:
def<-c("BAL","DEN","DEN")
home<-c("DEN","DEN","BAL")
away<-c("BAL","BAL","DEN")
def home away
1 BAL DEN BAL
2 DEN DEN BAL
3 DEN BAL DEN
My goal is to create a new column named def2
which will include the opposite team from the one that is included in the def
column. In order to find the name of that team it should check the values of home
and away
columns. The final dataset should be like:
def home away def2
1 BAL DEN BAL DEN
2 DEN DEN BAL BAL
3 DEN BAL DEN BAL
Upvotes: 2
Views: 82
Reputation: 9277
If df
is your dataframe, in base R you can use
df$def2 <- ifelse(df$def == df$home, df$away, df$home)
# def home away def2
# 1 BAL DEN BAL DEN
# 2 DEN DEN BAL BAL
# 3 DEN BAL DEN BAL
If you are in a dplyr
pipeline, you can use
library(dplyr)
df %>% mutate(def2 = if_else(def == home, away, home))
Upvotes: 3