Home > OS >  Split column with : and - symbols into multiple columns in R
Split column with : and - symbols into multiple columns in R

Time:11-18

I have a data like below:

SAMPLE  TYPE    INTERVAL    KB  CHR MID_BP  TARGETS NUM_TARG    Q_EXACT Q_SOME  Q_NON_DIPLOID   Q_START Q_STOP  MEAN_RD MEAN_ORIG_RD
BOBBY   DEL chrX:120065155-120119383    54.23   chrX    120092269   395..428    34  5   92  94  1   10  -1.88   13.13
JOHN    DUP chrX:134872056-134874055    2.00    chrX    134873055   440..442    3   40  54  54  27  19  4.32    105.48
JOHN    DUP chrX:134930172-134965407    35.24   chrX    134947789   447..455    9   6   89  90  6   46  2.76    79.67

I want to split inside the table the 3rd column named INTERVAL by : and - symbols like below:

a    b         c 
chrX 120065155 120119383

I tried this command line that separates only by :. How to split the column by both symbols?

df <- separate(data = df, col = INTERVAL, into = c("a", "b", "c"), sep = "\\:")

I could do like this, but may be there is a better way:

df$INTERVAL <-  gsub("-", ":", df$INTERVAL)
df <- separate(data = df, col = INTERVAL, into = c("a", "b", "c"), sep = "\\:")

CodePudding user response:

Use sep = "\\:|\\-"

df %>% 
  separate(INTERVAL, into=c("a", "b", "c"), sep = "\\:|\\-")
  • Related