Home > Net >  Delimit a column in R based on 2 characters
Delimit a column in R based on 2 characters

Time:01-06

I have a column in a dataframe in R that contains values such as

C22/00556,
C21/00445,
B22/00111,
C22-00679, etc.

I would like to split this into 2 columns named initial and number. The delimiter being "-" or "/". As a result I would expect a column containing C22, C21, B22, etc and another column containing 00556, 00445 etc.

I am trying to use the separate function but I am struggling with the sep= part. I have tried using sep= c("/","-") but this is not working and throws an error.

CodePudding user response:

You could use separate from tidyr by / or (|) - like this:

df <- data.frame(V1 = c("C22/00556", "C21/00445", "B22/00111", "C22-00679"))

library(tidyr)
df %>%
  separate(V1, c("initial", "number"), sep = "/|-")
#>   initial number
#> 1     C22  00556
#> 2     C21  00445
#> 3     B22  00111
#> 4     C22  00679

Created on 2023-01-05 with reprex v2.0.2

  • Related