How can you reverse a string of numbers in R?
for instance, I have a vector of about 1000 six digit numbers, and I would like to know if they are palindromes. I wo
Using intToUtf8 to split, then reverse:
tmp <- c(100001, 123321, 123456)
res <- sapply(tmp, function(i) intToUtf8(rev(utf8ToInt(as.character(i)))))
res
# [1] "100001" "123321" "654321"
To check if it is a palindrome:
tmp == res
# [1] TRUE TRUE FALSE
# bigger vector
tmpBIG <- rep(c(100001, 123321, 123456), 4000)
bench::mark(
GregSnow = { grepl( '^([0-9])([0-9])([0-9])\\3\\2\\1$', tmpBIG) },
bartektartanus = { tmpBIG == stringi::stri_reverse(tmpBIG) },
Spacedman = { tmpBIG == sub( '^([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])','\\6\\5\\4\\3\\2\\1', tmpBIG) },
Joshua = { tmpBIG == sapply(strsplit(as.character(tmpBIG),""), function(i) paste(rev(i),collapse="")) },
zx8754 = { tmpBIG == sapply(tmpBIG, function(i) intToUtf8(rev(utf8ToInt(as.character(i))))) },
relative = TRUE)[, 1:9]
# expression min median `itr/sec` mem_alloc `gc/sec` n_itr n_gc total_time
#
# 1 GregSnow 1 1 6.82 1 NaN 23 0 517ms
# 2 bartektartanus 1.38 1.34 5.02 2.33 NaN 17 0 520ms
# 3 Spacedman 1.58 1.55 4.52 2.33 NaN 15 0 509ms
# 4 Joshua 5.82 5.56 1.24 5.29 Inf 5 6 617ms
# 5 zx8754 6.06 6.17 1 3.98 Inf 4 4 614ms