分为3个字符长度

时间:2011-09-17 02:58:25

标签: r split character

我有一个非常简单的问题:如何在单个代码中将以下文本分成3个

mycodes <- c("ATTTGGGCTAATTTTGTTTCTTTCTGGGTCTCTC")
strsplit(mycodes, split = character(3), fixed = T, perl = FALSE, useBytes = FALSE)

[[1]]
 [1] "A" "T" "T" "T" "G" "G" "G" "C" "T" "A" "A" "T" "T" "T" "T" "G" "T" "T" "T" "C"
[21] "T" "T" "T" "C" "T" "G" "G" "G" "T" "C" "T" "C" "T" "C"

这不是我想要的;我一次想要三个字母:

[1] "ATT"  "TGG", "GCT"...............and so on the final may be of one, two or three letters depending upon the letter availability.

感谢;

3 个答案:

答案 0 :(得分:6)

我假设您想要使用密码子。如果是这种情况,您可能需要查看Bioconductor的Biostrings包。它提供了各种用于处理生物序列数据的工具。

library(Biostrings)
?codons

你可以通过一点点笨拙的强制来实现你想要的目标:

as.character(codons(DNAString(mycodes)))

答案 1 :(得分:2)

以下是使用stringr

的一种方法
require(stringr)
start = seq(1, nchar(mycodes), 3)
stop  = pmin(start + 2, nchar(mycodes))
str_sub(mycodes, start, stop)

输出

[1] "ATT" "TGG" "GCT" "AAT" "TTT" "GTT" "TCT" "TTC" "TGG"
[10] "GTC" "TCT" "C" 

答案 2 :(得分:1)

您也可以使用:

 strsplit(data, '(?<=.{3})', perl=TRUE)
[[1]]
 [1] "ATT" "TGG" "GCT" "AAT" "TTT" "GTT" "TCT" "TTC" "TGG" "GTC" "TCT" "C" 

library(stringi)
stri_extract_all_regex(data, '.{1,3}')