Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract last word in string in R

Tags:

r

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.

like image 930
user2030503 Avatar asked Jul 15 '13 15:07

user2030503


People also ask

How do I get the last letter of a string in R?

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.

How do I get part of a string in R?

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().


2 Answers

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" 
like image 162
leo Avatar answered Sep 20 '22 18:09

leo


tail(strsplit('this is a sentence',split=" ")[[1]],1) 

Basically as suggested by @Señor O.

like image 42
Roland Avatar answered Sep 18 '22 18:09

Roland