Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate string that contains "_"

Tags:

r

dplyr

tidyr

I have the following

ex <- tribble(
  ~type,
  "a__0",
  "ab__10"
)

> ex
type
a__0
ab__10

I would like to separate by "_". The result would be

letter  extra
a       __0
ab      __10

Note the double underscore

but when I use the following

ex %>% separate(type,into=c("letter","extra"),sep = "_")

I get

letter  extra
a       
ab      
like image 618
Alex Avatar asked Apr 30 '26 12:04

Alex


1 Answers

Insert a comma before the first underscore and then separate by comma:

ex %>% 
   mutate(type = sub("_", ",_", type)) %>% 
   separate(type, into = c("letter", "extra"), sep = ",")

giving:

# A tibble: 2 x 2
  letter extra
* <chr>  <chr>
1 a      __0  
2 ab     __10 
like image 53
G. Grothendieck Avatar answered May 02 '26 06:05

G. Grothendieck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!