[This article was first published on Steve's Data Tips and Tricks, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)


Want to share your content on R-bloggers? click here if you have a blog, or here if you don't. IntroductionGood morning, everyone!

Today, we’re going to talk about how to handle rows in your dataset that contain a specific string. This is a common task in data cleaning and can be easily accomplished using both base R and the dplyr package. We’ll go through examples for each method and break down the code so you can understand and apply it to your own data.

ExamplesUsing Base RFirst, let’s see how to select and drop rows containing a specific string using base R. We’ll use the grep() function for this.

Example DataLet’s create a simple data frame to work with:

data <- data.frame( id = 1:5, name = c("apple", "banana", "cherry", "date", "elderberry"), stringsAsFactors = FALSE)print(data)

id name1 1 apple2 2 banana3 3 cherry4 4 date5 5 elderberry Selecting Rows with a Specific StringSuppose we want to select rows where the name contains the letter “a”. We can use grep():

selected\_rows <- data[grep("a", data$name), ]print(selected\_rows)

id name1 1 apple2 2 banana4 4 date Explanation:

  • grep("a", data$name) searches for the letter “a” in the name column and returns the indices of the rows that match.
  • data[grep("a", data$name), ] uses these indices to subset the original data frame.

Dropping Rows with a Specific StringTo drop rows that contain the letter “a”, we can use the -grep() notation:

dropped\_rows <- data[-grep("a", data$name), ]print(dropped\_rows)

id name3 3 cherry5 5 elderberry Explanation:

  • -grep("a", data$name) returns the indices of the rows that do not match the search term.
  • data[-grep("a", data$name), ] subsets the original data frame by excluding these rows.

Using dplyrThe dplyr package makes these tasks even more straightforward with its intuitive functions.

Example DataWe’ll use the same data frame as before. First, make sure you have dplyr installed and loaded:

```

install.packages("dplyr")library(dplyr)

`` Selecting Rows with a Specific StringUsingdplyr, we can select rows containing “a” with thefilter()function combined withstr_detect()from thestringr` package:

library(stringr)selected\_rows\_dplyr <- data %>% filter(str\_detect(name, "a"))print(selected\_rows\_dplyr)

id name1 1 apple2 2 banana3 4 date Explanation:

  • %>% is the pipe operator, allowing us to chain functions together.
  • filter(str_detect(name, "a")) filters rows where the name column contains the letter “a”.

Dropping Rows with a Specific StringTo drop rows containing “a” using dplyr, we use filter() with the negation operator !:

dropped\_rows\_dplyr <- data %>% filter(!str\_detect(name, "a"))print(dropped\_rows\_dplyr)

id name1 3 cherry2 5 elderberry Explanation:

  • !str_detect(name, "a") negates the condition, filtering out rows where the name column contains the letter “a”.

SummaryBoth base R and dplyr provide powerful ways to select and drop rows based on specific strings. The grep() function in base R and the combination of filter() and str_detect() in dplyr are versatile tools for your data manipulation needs.

Give these examples a try with your own datasets! Experimenting with different strings and data structures will help reinforce these concepts and improve your data manipulation skills.

Happy coding!

To leave a comment for the author, please follow the link and comment on their blog: Steve's Data Tips and Tricks.


R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.


Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.Continue reading: How to Drop or Select Rows with a Specific String in R