Separating a column by the first 3 characters

26 Views Asked by At

I have a set of data below and I would like to separate the first three characters from the bm_id column into a separate column with the rest of the characters in another column.

bm_id
1 popCL20TE
2 agrST20
3 agrST20-09SE

I have tried using solutions to a similar question asked on stack, however I end up making extra empty columns with my data remaining together.

bm_id[c('species', 'id')] <- tstrsplit(bm_id$bm_id, '(?<=.{3})', perl = TRUE)

same happens with this code

bm_id2 <- tidyr::separate(bm_id, bm_id, into = c("species", "id"), sep = 3)
1

There are 1 best solutions below

0
Marco On

How about substr

df <- data.frame(vec= c("popCL20TE", "agrST20"))

df$first3 <- substr(df$vec, 1, 3)
df$last <- substr(df$vec, 4, nchar(df$vec)) 
df
        vec first3   last
1 popCL20TE    pop CL20TE
2   agrST20    agr   ST20