OneBite.Dev - Coding blog in a bite size

check if a string is a palindrome in R

Code snippet on how to check if a string is a palindrome in R

  is_palindrome <- function(str) { 
    rev_str <- paste0(strsplit(str, "")[[1]][length(str):1], 
                        collapse = "") 
    if (str == rev_str) return("TRUE") 
    else return("FALSE") 
  } 

This code uses a function to determine whether the input string is a palindrome or not. First, the function splits the string into individual characters and reverses their order, before combining them back together into a single word. Then, the original string is compared to the reversed word - if they are the same, the function returns “TRUE”, otherwise it returns “FALSE”. This code can be used to check if any string is a palindrome or not.

r