简体   繁体   中英

How to add column based on condition?

i know there were posts about this before, but the advise provided doesnt work in my case(

Below is the data frame i am using. What i want to do is to add another column "HomeWin" which will use info from column FTR and will put "W" if FTR = H, "L" if FTR = A and "D" if FTR = D.

 HomeTeam       AwayTeam      FTR 
1     Arsenal       Coventry   A
2 Aston Villa            QPR   H
3     Chelsea      Blackburn   A
4   Liverpool Sheffield Weds   H
5    Man City          Leeds   D
6   Newcastle      Tottenham   A

The results wanted is:

 HomeTeam       AwayTeam      FTR  HomeWin
1     Arsenal       Coventry   A     L
2 Aston Villa            QPR   H     W
3     Chelsea      Blackburn   A     L
4   Liverpool Sheffield Weds   H     W
5    Man City          Leeds   D     D
6   Newcastle      Tottenham   A     L

Just to be more clear below is the code i have written (its wrong and not full), but to make point more clearer:

season_1993_1994[, HomeWin := ifelse(FTR %in% c("A"), "L")]

Thanks a lot in advance!!!

您也可以使用qdap软件包中的multigsub:

df$HomeWin <- multigsub(c("A", "H", "D"), c("L", "W", "D"), df$FTR)
df$HomeWin = df$FTR
df$HomeWin[df$HomeWin == "A"] = "L"
df$HomeWin[df$HomeWin == "H"] = "W"

But as stated in the comment you could just not add this column and refer to the FTR column and just check for "A" and "H". This would save you needing a 4th column for no reason

You can also use the dplyr package and perform a left_join based on a dataframe which will be used as lookup table. Just add this code after your dataframe (assume your dataframe is called df) :

library(dplyr)
left_join(df,data.frame(FTR = c("A","H","D"),Homewin = c("L","W","D")))

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM