I am trying to find all the palindromic words in a column in a data frame 'data' which looks like:
name year amount
James 2010 934706
Aza 2010 21042
Rory 2010 869691
Suzanne 2010 651674
Felicity 2010 386115
Oliver 2010 382388
Anna 2010 43211
I have tried:
palindrome <- function(word) {
rawWord <- charToRaw(tolower(word)) ## converts to lower case
sprintf("%s is %sa palindrome", word,
c("not ", "")[identical(rawWord, rev(rawWord)) + 1])
}
palindrome(data)
But this returns a list of "mary is not a palindrome" "anna is not a palindrome" ... etc I want to be able to subset only the words that are palindromic and then return them to the data frame in order to correlate them to the other columns to find when they occured and how many times.
You can do the following steps.
rawdata <- sapply(tolower(data$name), charToRaw)
# Array of booleans. TRUE if palindromic. FALSE if not
ispalindrom <- unlist(lapply(rawdata, function(x) identical(x, rev(x))))
# Palindromic words
data[ispalindrom,]
# Non palindromic words
data[! ispalindrom,]