I have this kinda simple task I'm having hard time looping.
So, lets assume I have this tibble:
library(tidyverse)
dat <- tibble(player1 = c("aa","bb","cc"), player2 = c("cc","aa","bb"))
My goal here, is to make three new columns ( for each unique "player" I have) and assign value of 1 to the column, if the player is "player1", -1 if the player is "player2" and 0 otherwise.
Previously, I have been doing it like this:
dat %>% mutate( aa = ifelse(player1 == "aa",1,ifelse(player2 == "aa",-1,0)),
          bb = ifelse(player1 == "bb",1,ifelse(player2 == "bb",-1,0)),
          cc = ifelse(player1 == "cc",1,ifelse(player2 == "cc",-1,0)))
This works, but now I have hundreds of different "players", so it would seem silly to do this manually like that. I have tried and read about loops in R, but I just can't get this one right.
Using model.matrix() from base R:
dat[unique(dat$player1)] <- 
  model.matrix(~0+ player1, data = dat) - model.matrix(~0+ player2, data = dat)
dat
  player1 player2    aa    bb    cc
  <chr>   <chr>   <dbl> <dbl> <dbl>
1 aa      cc          1     0    -1
2 bb      aa         -1     1     0
3 cc      bb          0    -1     1
This assumes you have all players in both columns. Otherwise you would need to convert them to factors with the appropriate levels and replace unique with levels.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With