0

I need to add 3 new columns with values to another dataframe. The only issue is, that the columns im trying to bind aren't ordered correctly. Therefore i need to match values of rows in the dataframe i want to bind these columns to. Im trying to match the columns based on three existing columns. These are a date column and two different string columns.

df <- data.frame(Date = c("20170811", "20170811", "20170811"), 
                 HomeTeam = c("Brighton", "Leicster", "ManU"),
                 AWayTeam = c("Chelsea", "ManC", "Wolves"))
df2 <- data.frame(Date = c("20170811", "20170811", "20170811"), 
                  HomeTeam = c("Brighton", "Leicster", "ManU"),
                  AWayTeam = c("Chelsea", "ManC", "Wolves"), 
                  B1 = c(2.23, 2.54, 5.32),
                  B2 = c(2.43, 2.14, 5.22),
                  B3 = c(2.13, 2.55, 5.52))
head(df)
      Date HomeTeam AWayTeam
1 20170811 Brighton  Chelsea
2 20170811 Leicster     ManC
3 20170811     ManU   Wolves
head(df2)
      Date HomeTeam AWayTeam   B1   B2   B3
1 20170811 Brighton  Chelsea 2.23 2.43 2.13
2 20170811 Leicster     ManC 2.54 2.14 2.55
3 20170811     ManU   Wolves 5.32 5.22 5.52

My df is larger than this example, but the idea is the same. I need to bind column B1, B2 and B3 to df by somehow using Date, HomeTeam and AwayTeam as an argument but i simply cant figure it out.

Hope that this makes sense

  • A more efficient way will be to merge the tables rather than binding. `df_joined <- merge(df, df2, by = c("Date", "HomeTeam", "AWayTeam"))` Edited: "Away" to "AWay" – TheN Apr 19 '23 at 13:06

0 Answers0