Divide the column into multiple columns using tidyr :: separate with sep = ""

df <- data.frame(category = c("X", "Y"), sequence = c("AAT.G", "CCG-T"), stringsAsFactors = FALSE)

df
 category sequence
1        X     AAT.G
2        Y     CCG-T

I want to highlight a column sequenceof 5 columns (one for each character). I tried to do this with help tidyr::separate, but it internally uses stringi::stri_split_regexthat does not accept an empty string as a delimiter (although the argument sepmust accept a regular expression).

library(tidyr)
separate(df, sequence, into = paste0("V", 1:5), sep="")

Error: Values not split into 5 pieces at 1, 2
In addition: Warning messages:
1: In stringi::stri_split_regex(value, sep, n_max) :
  empty search patterns are not supported
2: In stringi::stri_split_regex(value, sep, n_max) :
  empty search patterns are not supported

The expected result is as follows:

  category V1 V2 V3 V4 V5
1        X  A  A  T  .  G
2        Y  C  C  G  -  T
+3
source share
2 answers

You can do it with help extractfromtidyr

library(tidyr)
extract(df, sequence, into=paste0('V', 1:5), '(.)(.)(.)(.)(.)')
#  category V1 V2 V3 V4 V5
#1        X  A  A  T  .  G
#2        Y  C  C  G  -  T

Or create a separator with gsuband use it as sepforseparator

library(dplyr)
library(tidyr)
df %>% 
   mutate(sequence=gsub('(?<=.)(?=.)', ',', sequence, perl=TRUE)) %>% 
   separate(sequence, into=paste0('V', 1:5), sep=",")
#  category V1 V2 V3 V4 V5
#1        X  A  A  T  .  G
#2        Y  C  C  G  -  T

Or you can use cSplit

library(splitstackshape)
setnames(cSplit(df, 'sequence', '', stripWhite=FALSE),
             2:6, paste0('V', 1:5))[]
#   category V1 V2 V3 V4 V5
#1:        X  A  A  T  .  G
#2:        Y  C  C  G  -  T
+3
source

sep . sep=1:4 5 .

df %>% separate(sequence, into = paste0("V", 1:5), sep = 1:5)

:

  category V1 V2 V3 V4 V5
1        X  A  A  T  .  G
2        Y  C  C  G  -  T
0

Source: https://habr.com/ru/post/1613862/


All Articles