tidyr separate column values into character and numeric using regex

Viewed 5228

I'd like to separate column values using tidyr::separate and a regex expression but am new to regex expressions

df <- data.frame(A=c("enc0","enc10","enc25","enc100","harab0","harab25","harab100","requi0","requi25","requi100"), stringsAsFactors=F) 

This is what I've tried

library(tidyr)
df %>%
   separate(A, c("name","value"), sep="[a-z]+")

Bad Output

   name value
1           0
2          10
3          25
4         100
5           0
# etc

How do I save the name column as well?

4 Answers

You could use the package unglue

library(unglue)
unglue_unnest(df, A, "{name=\\D+}{value}")
#>     name value
#> 1    enc     0
#> 2    enc    10
#> 3    enc    25
#> 4    enc   100
#> 5  harab     0
#> 6  harab    25
#> 7  harab   100
#> 8  requi     0
#> 9  requi    25
#> 10 requi   100

Created on 2019-10-08 by the reprex package (v0.3.0)

Related