Gabriel
Gabriel

Reputation: 425

Finding All occurrences of a string in a vector (grep(), which() functions don't quite work)

I have this spreadsheet and want to see how often the string "Drake" appears.

For example, some rows say "Drake, Kendrick Lamar, Post Malone" , but they're not being counted with the code I have:

data <- read.csv("C:/Users/Gabriel/Documents/responses.csv", header = TRUE)

artist <- data$artists
grep("Drake$", artist)

artistcount <- which('Drake' == artist)
artistcount

the results I get from grep() or which() are both

# 7 47 71

I want ALL rows where "Drake" appears. This code shows me which rows had "Drake" as the ONLY string. It should be way more than just 3 rows. I appreciate any feedback.

Here's an example of the data in the "artists" column:

enter image description here

Upvotes: 0

Views: 1055

Answers (1)

Jordan Wilcoxson
Jordan Wilcoxson

Reputation: 91

This can be done using the filter function from dplyr and str_detech from stringr.

 library(stringr)
 library(dplyr)
 data <- read.csv(choose.files())
 drake <- data %>%
   filter(str_detect(artists, "Drake"))

Upvotes: 1

Related Questions