2

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;

Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
John
  • 21
  • 2

3 Answers3

7

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)))
Jake
  • 5,379
  • 6
  • 19
  • 19
2

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}')
Prasanna Nandakumar
  • 4,295
  • 34
  • 63
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" 
Ramnath
  • 54,439
  • 16
  • 125
  • 152