R - reverse a string

31 May 2019

https://www.r-bloggers.com/four-ways-to-reverse-a-string-in-r/

1) strsplit() and paste() (base R) 2) utf8ToInt() and intToUtf8()</em> (base R) 3) stri_reverse() (stringi package) 4) str_rev() ( Biostrings package)

set.seed(1)
dna <- paste(sample(c("A", "T", "C", "G"), 10000000, replace = T), collapse = "")
# 1) Base R: strsplit and paste

splits <- strsplit(dna, "")[[1]]
reversed <- rev(splits)
final_result <- paste(reversed, collapse = "")


# 2) Base R: intToUtf8 and utf8ToInt

final_result <- intToUtf8(rev(utf8ToInt(dna)))


# 3) The stringi package
# (fastest)
	
library(stringi)
 
final_result <- stri_reverse(dna)


# 4) The Biostrings package

biocLite("Biostrings")
 
library(Biostrings)

final_result <- str_rev(dna)

[ R  function  string  ]