0

I am working on a tennis data set. I have a table of number of lost matches by player with 384 rows. I have a table of number of won matches by player with 287 rows. I want to create a column j where I can add the two-column 'n' if a player is in both tables. If not I want to add 0. Here is the code, but it doesn't work

for (i in num_match_l$Loser){
  num_match_l$b <-num_match_l$n + ifelse(i %in% num_match_w$Winner, num_match_w$n, 0)
}

Winner table

Loser and final table

camille
  • 16,432
  • 18
  • 38
  • 60
  • It would be easier to do a join using `merge` or `left_join` from the `dplyr` package on the `Winner and Loser` columns and then add the columns after that. – Kay Oct 16 '21 at 15:36
  • I'm glad it worked for you. I gave an illustration to show what I meant for others who may have the same question. You can accept the answer. – Kay Oct 16 '21 at 16:00
  • 1
    Does this answer your question? [How to join (merge) data frames (inner, outer, left, right)](https://stackoverflow.com/questions/1299871/how-to-join-merge-data-frames-inner-outer-left-right) – manro Oct 16 '21 at 16:25

1 Answers1

0

To illustrate what I said in my comment.

library(tidyverse)

num_match_w <- data.frame(Winner = c('Albot R', 'Alcaraz C', 'Altamaier D'),
                          n=c(49,1,3))

       Winner  n
1     Albot R 49
2   Alcaraz C  1
3 Altamaier D  3

num_match_l = data.frame(Loser = c('Ahouda A', 'Alcaraz C', 'Albot R'), 
                         n=c(1,57,1), b=c(50,106,50))

    Loser  n   b
1  Ahouda A  1  50
2 Alcaraz C 57 106
3   Albot R  1  50

num_match_w%>%left_join(num_match_l, by=c('Winner'='Loser'), suffix=c('_win','_loss'))%>%
 mutate(wins_and_losses=n_win+if_else(is.na(n_loss), 0, n_loss))

       Winner n_win n_loss   b wins_and_losses
1     Albot R    49      1  50              50
2   Alcaraz C     1     57 106              58
3 Altamaier D     3     NA  NA               3
Kay
  • 2,057
  • 3
  • 20
  • 29