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"

Example 1: Returning the First Word of a String Using the word() Function of stringr

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

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top