TransWikia.com

Add a new column to dataframe after comparing the values of other columns

Stack Overflow Asked by firmo23 on December 13, 2021

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

One Answer

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))

Answered by Ric S on December 13, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP