Pattern matching using a wildcard

前端 未结 5 693
野的像风
野的像风 2020-12-01 00:15

How do I identify a string using a wildcard?

I\'ve found glob2rx, but I don\'t quite understand how to use it. I tried using the following code to pick

5条回答
  •  天命终不由人
    2020-12-01 00:35

    glob2rx() converts a pattern including a wildcard into the equivalent regular expression. You then need to pass this regular expression onto one of R's pattern matching tools.

    If you want to match "blue*" where * has the usual wildcard, not regular expression, meaning we use glob2rx() to convert the wildcard pattern into a useful regular expression:

    > glob2rx("blue*")
    [1] "^blue"
    

    The returned object is a regular expression.

    Given your data:

    x <- c('red','blue1','blue2', 'red2')
    

    we can pattern match using grep() or similar tools:

    > grx <- glob2rx("blue*")
    > grep(grx, x)
    [1] 2 3
    > grep(grx, x, value = TRUE)
    [1] "blue1" "blue2"
    > grepl(grx, x)
    [1] FALSE  TRUE  TRUE FALSE
    

    As for the selecting rows problem you posted

    > a <- data.frame(x =  c('red','blue1','blue2', 'red2'))
    > with(a, a[grepl(grx, x), ])
    [1] blue1 blue2
    Levels: blue1 blue2 red red2
    > with(a, a[grep(grx, x), ])
    [1] blue1 blue2
    Levels: blue1 blue2 red red2
    

    or via subset():

    > with(a, subset(a, subset = grepl(grx, x)))
          x
    2 blue1
    3 blue2
    

    Hope that explains what grob2rx() does and how to use it?

提交回复
热议问题