0

So I have a data frame in R with a column that shows sports teams' win-loss record as a character, such as "7-5". How can I separate these into a numeric win column and a separate numeric loss column?

gshelor
  • 5
  • 2
  • 1
    In `dplyr` you could use `separate(tibble(win_loss = "7-5"), win_loss, into = c("win", "loss"), sep = "-")` – harre Aug 16 '22 at 20:02
  • here's an example of separate https://stackoverflow.com/questions/7069076/split-column-at-delimiter-in-data-frame – micah Aug 16 '22 at 20:03
  • 1
    Does this answer your question? [Split data frame string column into multiple columns](https://stackoverflow.com/questions/4350440/split-data-frame-string-column-into-multiple-columns) – harre Aug 16 '22 at 20:04

2 Answers2

0

You can try this

library(tidyverse)

new_df<- df %>% 
  separate(win_loss,c('win', 'loss'), sep = '-', convert = TRUE, remove = FALSE) 
amanwebb
  • 380
  • 2
  • 9
0

You can use separate() from tidyr to split a character column.

library(tidyverse)

df <- tibble(team = c("Team 1", "Team 2","Team 3"),
             w_l = c("2-0", "1-1", "0-2"))

df |> 
  # convert = TRUE turns the numbers into integers automatically
  separate(w_l, into = c("w", "l"), sep = "-", convert = TRUE)
#> # A tibble: 3 × 3
#>   team       w     l
#>   <chr>  <int> <int>
#> 1 Team 1     2     0
#> 2 Team 2     1     1
#> 3 Team 3     0     2

Created on 2022-08-16 by the reprex package (v2.0.1)

Camden Kay
  • 109
  • 5