I need to check if a row in one column contains the corresponding (numeric) value from the same row in another column for all rows.
If I only checked the string for one template, that would be simple using data.table likeor grepl. However, my template value is different for each row.
There is a somewhat related question here , but unlike this question, I need to create a boolean flag indicating whether a template is present.
Let's say this is my data set;
DT <- structure(list(category = c("administration", "nurse practitioner",
"trucking", "administration", "warehousing", "warehousing", "trucking",
"nurse practitioner", "nurse practitioner"), industry = c("admin",
"truck", "truck", "admin", "nurse", "admin", "truck", "nurse",
"truck")), .Names = c("category", "industry"), class = "data.frame", row.names = c(NA,
-9L))
setDT(DT)
> DT
category industry
1: administration admin
2: nurse practitioner truck
3: trucking truck
4: administration admin
5: warehousing nurse
6: warehousing admin
7: trucking truck
8: nurse practitioner nurse
9: nurse practitioner truck
My desired result would be the same:
> DT
matches
1: TRUE
2: FALSE
3: TRUE
4: TRUE
5: FALSE
6: FALSE
7: TRUE
8: TRUE
9: FALSE
Of course, 1 and 0 will be as good as TRUE and FALSE.
Here are some things I tried that didn't work:
apply(DT,1,grepl, pattern = DT[,2], x = DT[,1])
[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
> apply(DT,1,grepl, pattern = DT[,1], x = DT[,2])
[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
> grepl(DT[,2], DT[,1])
[1] FALSE
> DT[Vectorize(grepl)(industry, category, fixed = TRUE)]
category industry
1: administration admin
2: trucking truck
3: administration admin
4: trucking truck
5: nurse practitioner nurse
> DT[stringi::stri_detect_fixed(category, industry)]
category industry
1: administration admin
2: trucking truck
3: administration admin
4: trucking truck
5: nurse practitioner nurse
> for(i in 1:nrow(DT)){print(grepl(DT[i,2], DT[i,1]))}
[1] FALSE
[1] FALSE
[1] FALSE
[1] FALSE
[1] FALSE
[1] FALSE
[1] FALSE
[1] FALSE
[1] FALSE
> for(i in 1:nrow(DT)){print(grepl(DT[i,2], DT[i,1], fixed = T))}
[1] FALSE
[1] FALSE
[1] FALSE
[1] FALSE
[1] FALSE
[1] FALSE
[1] FALSE
[1] FALSE
[1] FALSE
> DT[category %like% industry]
category industry
1: administration admin
2: administration admin
Warning message:
In grepl(pattern, vector) :
argument 'pattern' has length > 1 and only the first element will be used