select a value based on other values in the same row

We can use the functions found in the tidyverse package:

library(tidyverse)
dat %>%
  # create single winner and loser columns,
  # concatenating name and rank together
  unite(Winner, Winner, WRank, sep = "-") %>%
  unite(Loser, Loser, LRank, sep = "-") %>%
  # pivot to be "tall"
  pivot_longer(cols = c("Winner", "Loser")) %>%
  select(-name) %>%
  # reverse concatentation
  separate(value, into = c("Name", "Rank"), sep = "-")

 #   Date       Name           Rank 
 # 1 2000-01-03 Federer_R.     65   
 # 2 2000-01-03 Knippschild J. 87   
 # 3 2000-01-03 Enqvist_T.     5    
 # 4 2000-01-03 Federer R.     65   
 # 5 2000-01-10 Ferrero_J.C.   45   
 # 6 2000-01-10 Federer R.     61   
 # 7 2000-01-17 Federer_R.     62   
 # 8 2000-01-17 Chang M.       38   
 # 9 2000-01-17 Federer_R.     62   
 #10 2000-01-17 Kroslak J.     104  
 #11 2000-01-17 Clement_A.     54   
 #12 2000-01-17 Federer R.     62   

One thing to note is that this will convert your Rank to a character value. You can reverse that using the as.numeric function.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top