development

여러 패턴의 문자형 벡터를 사용하여 grep

big-blog 2020. 7. 14. 07:43
반응형

여러 패턴의 문자형 벡터를 사용하여 grep


I를 사용하는 것을 시도하고 grep있는 (패턴 매칭)되는 값을 문자열 벡터가 다른 벡터 아닌지에 존재하는지 여부를 검사하고, 출력한다.

다음과 같은 데이터 프레임이 있습니다.

FirstName Letter   
Alex      A1
Alex      A6
Alex      A7
Bob       A1
Chris     A9
Chris     A6

"Letter"열에서 찾을 수있는 문자열 패턴의 벡터가 있습니다 (예 :) c("A1", "A9", "A6").

패턴 벡터의 문자열이 "Letter"열에 있는지 확인하고 싶습니다. 그렇다면 고유 값의 출력을 원합니다.

문제는 grep여러 패턴 으로 사용하는 방법을 모른다는 것 입니다. 나는 시도했다 :

matches <- unique (
    grep("A1| A9 | A6", myfile$Letter, value=TRUE, fixed=TRUE)
)

그러나 그것은 사실이 아닌 0 개의 일치 항목을 제공합니다.


를 포함하지 않는 것에 대한 @Marek의 의견 외에도 fixed==TRUE정규 표현식에 공백이 없어도됩니다. 이어야합니다 "A1|A9|A6".

또한 많은 패턴이 있다고 언급합니다. 그들이 벡터에 있다고 가정

toMatch <- c("A1", "A9", "A6")

그런 다음 여기에서 직접 정규식을 만들 수 있습니다.

matches <- unique (grep(paste(toMatch,collapse="|"), 
                        myfile$Letter, value=TRUE))

좋은 답변이지만 filter()dplyr을 잊지 마십시오.

patterns <- c("A1", "A9", "A6")
>your_df
  FirstName Letter
1      Alex     A1
2      Alex     A6
3      Alex     A7
4       Bob     A1
5     Chris     A9
6     Chris     A6

result <- filter(your_df, grepl(paste(patterns, collapse="|"), Letter))

>result
  FirstName Letter
1      Alex     A1
2      Alex     A6
3       Bob     A1
4     Chris     A9
5     Chris     A6

Brian Digg의 게시물을 기반으로 목록을 필터링하는 데 유용한 두 가지 기능이 있습니다.

#Returns all items in a list that are not contained in toMatch
#toMatch can be a single item or a list of items
exclude <- function (theList, toMatch){
  return(setdiff(theList,include(theList,toMatch)))
}

#Returns all items in a list that ARE contained in toMatch
#toMatch can be a single item or a list of items
include <- function (theList, toMatch){
  matches <- unique (grep(paste(toMatch,collapse="|"), 
                          theList, value=TRUE))
  return(matches)
}

이 답변이 이미 있는지 확실하지 않습니다 ...

질문의 특정 패턴에 대해서는 한 번의 grep()호출로 수행 할 수 있습니다 .

grep("A[169]", myfile$Letter)

이것은 작동해야합니다 :

grep(pattern = 'A1|A9|A6', x = myfile$Letter)

또는 더 간단하게 :

myfile$Letter %like% 'A1|A9|A6'

match()또는 charmatch()기능 을 사용해 보셨습니까 ?

사용 예 :

match(c("A1", "A9", "A6"), myfile$Letter)

Brian Diggs의 답변에 추가하십시오.

grepl을 사용하는 다른 방법은 모든 값을 포함하는 데이터 프레임을 반환합니다.

toMatch <- myfile$Letter

matches <- myfile[grepl(paste(toMatch, collapse="|"), myfile$Letter), ]

matches

Letter Firstname
1     A1      Alex 
2     A6      Alex 
4     A1       Bob 
5     A9     Chris 
6     A6     Chris

Maybe a bit cleaner... maybe?


Take away the spaces. So do:

matches <- unique(grep("A1|A9|A6", myfile$Letter, value=TRUE, fixed=TRUE))

Using the sapply

 patterns <- c("A1", "A9", "A6")
         df <- data.frame(name=c("A","Ale","Al","lex","x"),Letters=c("A1","A2","A9","A1","A9"))



   name Letters
1    A      A1
2  Ale      A2
3   Al      A9
4  lex      A1
5    x      A9


 df[unlist(sapply(patterns, grep, df$Letters, USE.NAMES = F)), ]
  name Letters
1    A      A1
4  lex      A1
3   Al      A9
5    x      A9

I suggest writing a little script and doing multiple searches with Grep. I've never found a way to search for multiple patterns, and believe me, I've looked!

Like so, your shell file, with an embedded string:

 #!/bin/bash 
 grep *A6* "Alex A1 Alex A6 Alex A7 Bob A1 Chris A9 Chris A6";
 grep *A7* "Alex A1 Alex A6 Alex A7 Bob A1 Chris A9 Chris A6";
 grep *A8* "Alex A1 Alex A6 Alex A7 Bob A1 Chris A9 Chris A6";

Then run by typing myshell.sh.

If you want to be able to pass in the string on the command line, do it like this, with a shell argument--this is bash notation btw:

 #!/bin/bash 
 $stingtomatch = "${1}";
 grep *A6* "${stingtomatch}";
 grep *A7* "${stingtomatch}";
 grep *A8* "${stingtomatch}";

And so forth.

If there are a lot of patterns to match, you can put it in a for loop.

참고URL : https://stackoverflow.com/questions/7597559/grep-using-a-character-vector-with-multiple-patterns

반응형