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
Run Code Online (Sandbox Code Playgroud)
我想将该列sequence分为5列(每个字符一个)。我试图这样做,tidyr::separate但它在内部使用了stringi::stri_split_regex不接受空字符串作为分隔符的方式(尽管sep参数应使用正则表达式)。
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
Run Code Online (Sandbox Code Playgroud)
预期的输出如下所示:
category V1 V2 V3 V4 V5
1 X A A T . G
2 Y C C G - T
Run Code Online (Sandbox Code Playgroud)
你可以用extractfrom来做到这一点tidyr
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
Run Code Online (Sandbox Code Playgroud)
或者创建一个分隔符gsub并将其sep用作separator
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
Run Code Online (Sandbox Code Playgroud)
或者你可以使用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
Run Code Online (Sandbox Code Playgroud)