Split into 3 character length

让人想犯罪 __ 提交于 2019-12-24 11:12:08

问题


I have very simple question: How can I divide the following text into 3 in a single code

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"

This is not what I want; I want three letters at a time:

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

Thanks;


回答1:


I assume you want to work with codons. If that's the case, you might want to look at the Biostrings package from Bioconductor. It provides a variety of tools for working with biological sequence data.

library(Biostrings)
?codons

You can achieve what you want, with a little bit of clumsy coercion:

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



回答2:


Here is one approach using stringr package

require(stringr)
start = seq(1, nchar(mycodes), 3)
stop  = pmin(start + 2, nchar(mycodes))
str_sub(mycodes, start, stop)

Output is

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



回答3:


You can also use:

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

or

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


来源:https://stackoverflow.com/questions/7452156/split-into-3-character-length

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!