What's the most elegant way to extract the last word in a sentence string?
The sentence does not end with a "." Words are seperated by blanks.
sentence <- "The quick brown fox" TheFunction(sentence)
should return: "fox"
I do not want to use a package if a simple solution is possible. If a simple solution based on package exists, that is also fine.
To get the last n characters from a string, we can use the stri_sub() function from a stringi package in R. The stri_sub() function takes 3 arguments, the first one is a string, second is start position, third is end position.
The substring function in R can be used either to extract parts of character strings, or to change the values of parts of character strings. substring of a vector or column in R can be extracted using substr() function. To extract the substring of the column in R we use functions like substr() and substring().
Just for completeness: The library stringr contains a function for exactly this problem.
library(stringr) sentence <- "The quick brown fox" word(sentence,-1) [1] "fox"
tail(strsplit('this is a sentence',split=" ")[[1]],1)
Basically as suggested by @Señor O.
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