Get First & Last Word of Character String in R (2 Examples)
In this R programming tutorial you’ll learn how to find the first and last word of a character string.
Creation of Exemplifying Data
x <- "some crazy random words" # Construct example character string x # [1] "some crazy random words" |
x <- "some crazy random words" # Construct example character string x # [1] "some crazy random words"
Example 1: Returning the First Word of a String Using the word() Function of stringr
word(x, 1) # Get last word # [1] "some" |
word(x, 1) # Get last word # [1] "some"
Example 2: Returning the Last Word of a String Using the word() Function of stringr
install.packages("stringr") # Install stringr package library("stringr") # Load stringr package |
install.packages("stringr") # Install stringr package library("stringr") # Load stringr package
word(x, - 1) # Get last word # [1] "words" |
word(x, - 1) # Get last word # [1] "words"
Related Articles & Further Resources
Below, you can find some further resources that are similar to the content of this post.