I'm trying to learn r and I came accross an exerscie that I dont know how to solve. I'm trying to write a function that takes a string as argument and flips the characters of each word.
For example:
sentence.flipper("the quick brown fox jumped over the lazy dog")
should return "eht kciuq nworb xof depmuj revo eht yzal god"
So far I have written this
sentence.flipper = function(str) {
str.words = strsplit(str, split=" ")
rev.words = lapply(str.words, word.flipper)
str.flipped = paste(rev.words, sep=" ")
return(str.flipped)
}
word.flipper = function(str) {
#browser()
chars = strsplit(str, split=" ")
chars.flipped = rev(chars)
str.flipped = paste(chars.flipped , collapse=" ")
return(str.flipped)
but this returns
"dog lazy the over jumped fox brown quick the"
how can I fix this to get the desired output?
First split the sentence in words, then split each word into character, reverse them and paste them together.
sentence.flipper = function(str) {
paste0(sapply(strsplit(strsplit(str, '\\s+')[[1]], ''),
function(x) paste0(rev(x), collapse = '')), collapse = ' ')
}
sent <- "the quick brown fox jumped over the lazy dog"
sentence.flipper(sent)
#[1] "eht kciuq nworb xof depmuj revo eht yzal god"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With