Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Split a column into multiple column by pattern [closed]

Tags:

split

r

I want to separate the digits and character in a column of a dataframe d.df:

col1 
ab 12 14 56
xb 23 234 2342 2
ad 23 45

Expected output:

col1   col2
ab     12 14 56
xb     23 234 2342 2
ad     23 45

I recognize it will be something similar to this, but I'm not sure about the separators

t <- as.data.frame(str_match(d$col1,"^(.*)"))

I tried many methods and the output was:

col1      col2      
a         b 12 14 56
x         b  23 234 2342 2
a         d  23 45
like image 756
Lucia Avatar asked Aug 02 '26 01:08

Lucia


2 Answers

You can use separate from tidyr.

library(tidyr)
d.df %>% separate(col1, c("col1", "col2"), sep="(?<=[a-z]{2} )")
#   col1           col2
# 1   ab       12 14 56
# 2   xb  23 234 2342 2
# 3   ad          23 45

The regex, "(?<=[a-z]{2} )", is a look-behind, meaning "split at the position in the string after two lower case characters followed by a space". tidyr seems to have a limit on the length of look-behinds, so {2} is used to specify the number of letters.

like image 167
Rorschach Avatar answered Aug 04 '26 16:08

Rorschach


Here is an option with data.table.

 library(data.table)#v1.9.5+
 setnames(setDT(df1)[, tstrsplit(col1,
        '(?<=[^0-9]) (?=[0-9])', perl=TRUE)], paste0('col', 1:2))[]
 #   col1          col2
 #1:   ab      12 14 56
 #2:   xb 23 234 2342 2
 #3:   ad         23 45

We convert the 'data.frame' to 'data.table' (setDT(df1)). Using tstrsplit from the devel version of 'data.table', split at the space in 'col1' by matching the space after a letter and before a numeric part. We use regex lookarounds ((?<=[^0-9]) and ((?=[0-9])) for matching.

like image 29
akrun Avatar answered Aug 04 '26 15:08

akrun



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!