Reputation: 2017
I have the following dataframe:
data <- data.frame(MOBILE_NUMBER = c(
"999/277-135",
"075-788-476",
"078-388-607",
"077/969-557",
"076/423-130"))
And I want to create a boolean variable if the first 7 characters in the string match one of the values in the following vector:
list_values <- c("071", "072", "073", "074", "075", "076", "077", "078", "079")
I can pull the values with the following grep code:
grep(paste(list_values,collapse="|"),
data$MOBILE_NUMBER, value=TRUE))
But i'm not sure how to put this in a ifelse statement, and especially how to text it only on the first 7 elements of the string.
Anyone?
Upvotes: 2
Views: 451
Reputation: 887148
We can use substr
to get the substring of 1st 7 chararacters, apply the grepl
on it and convert it to binary (if needed) using as.integer
as.integer(grepl(paste(list_values,collapse="|"), substr(data[[1]], 1, 7)))
Upvotes: 1