More code chalenge on http://rpubs.com/elsiormoreira CODE LAB post.

A word is palindrome if does not change when its letters are reversed. Common examples are: civic, level, rotator, rotor, kayak, racecar. Phrases and sentences can also be palindromes (in these cases spaces, letter case and punctuation are ignored).

There is a simple way to check whether a word is a palindrome:

  1. Extract the letters from the word.
  2. Reverse their order.
  3. Paste them back together into a word.
  4. Compare with the original word.

Exercise and Solution

Basic Challenge: Develop a function that given a string (single word), check if it is a palindrome.

is_palindrome <- function(word) {
        library(stringr)
        split_word <- unlist((str_split(word, pattern = "")))
        reverse_word <- split_word[str_length(word):1]
        paste_word <- paste(reverse_word, collapse = "")
        cat(word == paste_word)
}

Understand the Answer

The above function check if a word is or not a palindrome. Copy and paste this code to your IDE and test it.

In the first line we load the stringr library. Without that our function doesn’t work proprerly because some commands come from stringr package. Next, in the second line, we split the given word. A vector was created containing each letter extracted from a given word. After that, in the third line, the function reverse the letter order. In the fourth, all reversed letters are pasted together. And finally, in the last line, the original and the reversed word are compared to check if they are palindrome.

Let’s test our function with some examples:

is_palindrome("civic")
TRUE
is_palindrome("great")
FALSE

As you can see, our function seems to work perfectly. But if we use upper case words or numbers instead of just usual lower case words? How about that? Let’s take a look.

is_palindrome("civIc")
FALSE

As you can see, we create a case sensitive function what is not helpful in some cases. It’s possible to convert case of a string using str_to_lower function from stringr package. Let’s adjust our function insert the first line below in our preview code.

is_palindrome <- function(word) {
        library(stringr)
        word <- str_to_lower(word)
        split_word <- unlist((str_split(word, pattern = "")))
        reverse_word <- split_word[str_length(word):1]
        paste_word <- paste(reverse_word, collapse = "")
        cat(word == paste_word)
}