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?
CodePudding user response:
You can try this
library(tidyverse)
new_df<- df %>%
separate(win_loss,c('win', 'loss'), sep = '-', convert = TRUE, remove = FALSE)
CodePudding user response:
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)