Reputation: 35
Newbie to R here. Been searching this forum to try and find a way to search for text within a string in the same row of data. I've used grepl before, but I can't get it to look down a column and apply the check for each row. I feel like this is an easy solution, but I've spent a few hours on it and can't seem to get it.
Basically I have something like column 1 below and need it to check if the text in column 2 is within column one, then return true or false in a new column.
column 1 column2 result
Target_US_Toy _US_ TRUE
Target_CA_Toy _MX_ FALSE
Target_NZ_Toy _NZ_ TRUE
Thank you!
Upvotes: 2
Views: 1920
Reputation: 263301
The base method would be to use mapply
to deliver a "parallel" set of arguments to a function that is not vectorized in one or more of its argument positions:
dat$ result <- mapply(grepl, dat$column2, dat$column1)
> dat
column1 column2 result
1 Target_US_Toy _US_ TRUE
2 Target_CA_Toy _MX_ FALSE
3 Target_NZ_Toy _NZ_ TRUE
Upvotes: 0
Reputation: 11128
You can also use grepl
with Map
unlist(Map(grepl, df$column2, df$column1))
Output:
#_US_ _MX_ _NZ_
#TRUE FALSE TRUE
Upvotes: 0
Reputation: 2056
Using str_detect
from the stringr
pacakge:
library(stringr)
str_detect(df1$column1, df1$column2)
[1] TRUE FALSE TRUE
or using only base R combining grepl
with apply:
apply(df1,1, function(x){
grepl(x[2], x[1])
})
[1] TRUE FALSE TRUE
Upvotes: 2
Reputation: 5689
We can do this using stringr
.
First, let's create a data frame:
df <- data.frame(column1 = c("Target_US_Toy", "Target_CA_Toy"),
column2 = c("_US_", "_NZ_"),
stringsAsFactors = FALSE)
Next, we create a new column called result
:
library(stringr)
df$result = str_detect(string = df$column1, pattern = df$column2)
Upvotes: 1