Home > Enterprise >  adding two columns of two different tables in Rstudio
adding two columns of two different tables in Rstudio

Time:10-17

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

CodePudding user response:

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
  • Related