Q:

Free text categorization through grep in R

I am an R newbie. I need to categorize free text (customer feedback) into given fixed number of categories. I am trying to run a small code to test the logic.
a<-c("a","b","c","d","e") # Category a - if the free text contains any of "a","b","c","d" or "e"
b<-c("f","g","h","i","j") # Category b - if the free text contains any of "f","g","h","i" or "j"
check<-c("a","g","d","j") # Free text to be categorized. "a" should be categorized as a; "g" as b; "d" as a and
                          # "j" as b
count<-length(check)
output<-vector(mode="list",length = count) # Empty categorized list - targeted output is (a,b,a,b)
for (i in 1:count) {
 output[i]<-ifelse(grepl(a,check[i]),"a",ifelse(grepl(b,check[i]),"b","other"))
}

I get the following warnings:
1. In grepl(a, check[i]) :
  argument 'pattern' has length > 1 and only the first element will be used
2. In grepl(a, check[i]) :
  argument 'pattern' has length > 1 and only the first element will be used
3. In grepl(b, check[i]) :
  argument 'pattern' has length > 1 and only the first element will be used
4. In grepl(a, check[i]) :
  argument 'pattern' has length > 1 and only the first element will be used
5. In grepl(b, check[i]) :
  argument 'pattern' has length > 1 and only the first element will be used
6. In grepl(a, check[i]) :
  argument 'pattern' has length > 1 and only the first element will be used
7. In grepl(b, check[i]) :
  argument 'pattern' has length > 1 and only the first element will be used

Output comes out as (a, other, other, other)
Either grepl is not the right function to use, or maybe there is a way to use vector pattern.
Request your help and guidance.

A:

grepl complains because the 'pattern' (the first argument) contains multiple patterns instead of just one. One way to solve this would be to collapse your conditions into one regular expression (the | denotes 'or'), such as this:
a<-c("a","b","c","d","e") # Category a - if the free text contains any of "a","b","c","d" or "e"
b<-c("f","g","h","i","j") # Category b - if the free text contains any of "f","g","h","i" or "j"
check<-c("a","g","d","j") # Free text to be categorized. "a" should be categorized as a; "g" as b; "d" as a and
# "j" as b

# collapse regular expression
a <- paste(a, collapse = "|")
b <- paste(b, collapse = "|")

count<-length(check)
output<-vector(mode="list",length = count) # Empty categorized list - targeted output is (a,b,a,b)
for (i in 1:count) {
  output[i]<-ifelse(grepl(a,check[i]),"a",ifelse(grepl(b,check[i]),"b","other"))
}

output

which returns
[[1]]
[1] "a"

[[2]]
[1] "b"

[[3]]
[1] "a"

[[4]]
[1] "b"

