check if a string starts with another string in R

Check If a String in R starts with Another String

In this tutorial, we will look at how to check whether a string in R starts with a specific string (or character) or not with the help of examples.

How to check if a string in R begins with a specific string?

From the R version 3.3.0, you can use the built-in startsWith() function to check whether a string starts with a particular string or not.

Pass the string and the starting pattern string as arguments to the startsWith() function. The following is the syntax –

# check if string str starts with the string pattern
startsWith(str, pattern)

It returns TRUE if the string str starts with the string pattern.

Examples

Let’s now look at some examples of using the above syntax.

Check if a string starts with a particular character in R

Here, we will create a sample string and check whether it begins with the character “A” or not.

# create a string
s <- "Avengers Endgame"
# check if s starts with "A"
print(startsWith(s, "A"))

Output:

[1] TRUE

We get TRUE as the output, because the string “Avengers Endgame” does start with the letter “A”.

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

Note that the startsWith() function performs a case-sensitive match. For example, let’s check whether the string “Avengers Endgame” starts with the letter “A”.

# create a string
s <- "Avengers Endgame"
# check if s starts with "a"
print(startsWith(s, "a"))

Output:

[1] FALSE

We get FALSE as the output.

Check if a string starts with a particular string in R

You can also use the startsWith() function to check if the string begins with a particular string (with more than one character) or not.

Let’s look at an example.

# create a string
s <- "mango"
# check if s starts with "man"
print(startsWith(s, "man"))

Output:

[1] TRUE

Here, we check if the string “mango” starts with the string “man”. We get TRUE as the output because “mango” does, in fact, start with the string “man”.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top