Separating a column by using regex expressions

Viewed 31

I have a data frame like this:

tibble(x = c("asdh.1", "asdh.1.1", "cccc.1.1", "asdh.1.2", "cccc.1.2", "asdh.1.11", "cccc.1.11"))
# A tibble: 7 x 1
  x        
  <chr>    
1 asdh.1   
2 asdh.1.1 
3 cccc.1.1 
4 asdh.1.2 
5 cccc.1.2 
6 asdh.1.11
7 cccc.1.11

Now I would like to split the column x into 2 columns such that the second column only contains the digits after the last dot, and the first column everything before the last dot. I tried messing around with regex but did not accomplish the desired outcome. The closest I got might be %>% separate(col=x, into=c("y", "numbers"), sep="(.*)\\.([1-9]{1,2}$)") but that gives only two empty columns.

1 Answers

We can specify a regex lookaround in separate to match the . (. is a metacharacter that matches any character - so we escape \\) followed by one or more digits (\\d+) at the end ($) of the string

library(tidyr)
separate(df1, col = x, into = c("y", "numbers"), 
       sep = "\\.(?=\\d+$)", convert = TRUE)
Related