Mary
Mary

Reputation: 57

Find a word in a string in R

I am looking for a command that solves the following task. So I have a vector containing urls as strings like:

urls <- c("https//:www.I-like.apples/hello.com",
          "https//:www.I-eat-apples-every-day.com",
          "https//:www.apples-are-red.com")

I need a command that assign 0 if the string doesn't contain the word apples and 1 if it does. These 0sand 1s will be stored in another vector of the same legth of the string vector.

Upvotes: 2

Views: 3359

Answers (2)

Caitlin
Caitlin

Reputation: 525

You can use stringr.

library(stringr)

new_vector <- ifelse(str_detect(urls, "apples"), 1, 0)

new_vector
# [1] 1 1 1

Upvotes: 0

akrun
akrun

Reputation: 886948

We can use grepl to return a logical vector and convert to binary with +

v2 <-  +(grepl("apples", urls))

Upvotes: 4

Related Questions