6

This is a follow-up question from here: Subsetting a string based on pre- and suffix

When you have this command:

    d <- subset(b, b$X %in% test)  

This command look for all in b$X that exactly matches test. How can I manipulate it to say its enough that the values in b$X contains test?
I.e. if b$X has a value "something" and test has "thing". Then I would regard this as a match.

Important update! Test has 512 values, not only 1 as in the example.

Community
  • 1
  • 1
user3236594
  • 157
  • 1
  • 4
  • 10

2 Answers2

12

You can replace %in% with grepl:

# examples
x <- c("thing", "something", "some", "else")
test <- c("thing", "some")

# exact match
x %in% test
# [1]  TRUE FALSE  TRUE FALSE

# substring match (regex)
pattern <- paste(test, collapse = "|") # create regex pattern
grepl(pattern, x)
# [1]  TRUE  TRUE  TRUE FALSE

The whole command for your task:

d <- subset(b, grepl(paste(test, collapse= "|"), b$X))

The "|" means logical or in regular expressions.

Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
  • I may have miss-leaded you. test has 512 different values. I guess that why I get "argument 'pattern' has length > 1 and only the first element will be used" ? – user3236594 Jan 28 '14 at 14:59
  • Thank you very much! It works like a charm. But I still can't find all my 512 names, only 287. With exact test I found only 256. Its nothing wrong with the codes, it must be something else... – user3236594 Jan 28 '14 at 15:15
  • a little late here to help you @user3236594, but the problem may be with order. The `grepl(paste(test, collapse= "|")` matches either thingsome or thing or some or something but not, "thing blah some". You need to do `grepl(thing, b$x) & grepl(some, b$x)` to make it work in that case. – jessi Aug 23 '14 at 21:36
0

No need for b$ in subset.

d <- subset(b, grepl(paste(test, collapse= "|"), X))
ArtemP
  • 1
  • 1
    It may be helpful to explain what you have changed from the original code, and why. This will make your answer more useful to future visitors. – miken32 May 03 '16 at 17:04