简体   繁体   中英

Matching data.frames in R

I have two data.frames of equal length. One data.frame has variables WEEK,Winner,Loser,homeScore,awayScore.

    'data.frame':   256 obs. of  5 variables:
 $ Week     : int  313 313 313 313 313 313 313 313 313 313 ...
 $ Winner   : Factor w/ 32 levels "ARI","ATL","BAL",..: 1 2 4 5 7 10 11 13 17 18 ...
 $ Loser    : Factor w/ 32 levels "ARI","ATL","BAL",..: 26 20 6 30 3 14 21 32 19 29 ...
 $ homeScore: Factor w/ 41 levels "","12","13","14",..: 7 25 12 9 12 20 23 6 21 22 ...
 $ awayScore: Factor w/ 32 levels "","0","10","11",..: 10 26 13 7 9 17 7 30 13 30 ...
> 

The other has WEEK, Favorite,Underdog,Spread.

'data.frame':   256 obs. of  4 variables:
 $ Week    : int  313 313 313 313 313 313 313 313 313 313 ...
 $ Favorite: chr  "SEA" "NO" "STL" "PIT" ...
 $ Underdog: Factor w/ 32 levels "ARI","ATL","BAL",..: 12 2 18 8 15 23 7 4 32 31 ...
 $ Spread  : chr  "-5" "-3" "-3" "-6" ...

I need to combine these two data.frames to have a data.frame with the WEEK, Favorite,Underdog,homeScore,awayScore, Spread.

I'm struggling with this matching issue because the Favorite may not be the Winner from the other data.frame.. So i need to go through each week match the Favorite with the Winner or Loser and place the spread in the correct row. I am new with R so this should be easy to do but its beyond my skills. Thanks for any help

..ok heres what the data.frames look like

head(df1)
  Week Winner Loser homeScore awayScore
   313    ARI    SD        18        17
   313    ATL    NO        37        34
   313    BUF   CHI        23        20
   313    CAR    TB        20        14
   313    CIN   BAL        23        16
   313    DEN   IND        31        24
   313    DET   NYG        35        14
   313    HOU   WAS        17         6
   313    MIA    NE        33        20
   313    MIN   STL        34         6

head(df2)
   Week Favorite Underdog Spread
    313      SEA       GB     -5
    313       NO      ATL     -3
    313      STL      MIN     -3
    313      PIT      CLE     -6
    313      PHI      JAX    -10
    313      NYJ      OAK   -6.5
    313      BAL      CIN     -1
    313      CHI      BUF     -7
    313      HOU      WAS     -3
    313       KC      TEN     -3

You need cbind() .

If your first data frame is A and second is B, first select the common WEEK for each:

subset.A <- subset(A, Week == 313)
subset.B <- subset(B, Week == 313)

Then combine them:

resultDF <- cbind(A$Week, B$Favorite, B$Underdog, A$homeScore, A$awayScore, B$Spread)

I don't know if I understood you correctly, but I kind of asked the same question some days ago. The best answer for me was:

 merge(DFa, DFb, by.x='columnName_a_2Match', by.y='columnName_b_2Match')

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