여러 패턴이 있는 문자 벡터를 사용한 grep
사용하려고 합니다.grep
문자열의 벡터가 다른 벡터에 존재하는지 여부를 테스트하고 존재하는 값(일치하는 패턴)을 출력합니다.
다음과 같은 데이터 프레임이 있습니다.
FirstName Letter
Alex A1
Alex A6
Alex A7
Bob A1
Chris A9
Chris A6
"편지" 열에서 찾을 수 있는 문자열 패턴 벡터가 있습니다. 예:c("A1", "A9", "A6")
.
패턴 벡터에 있는 문자열이 "편지" 열에 있는지 확인하고 싶습니다.만약 그렇다면, 저는 고유한 값의 출력을 원합니다.
문제는, 어떻게 사용해야 할지 모른다는 것입니다.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")
그런 다음 다음 다음을 사용하여 직접 정규식을 만들 수 있습니다.paste
그리고.collapse = "|"
.
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
이렇게 하면 됩니다.
grep(pattern = 'A1|A9|A6', x = myfile$Letter)
또는 더 간단하게는:
library(data.table)
myfile$Letter %like% 'A1|A9|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)
}
사용해 보셨습니까?match()
또는charmatch()
함수?
사용 예:
match(c("A1", "A9", "A6"), myfile$Letter)
브라이언 긱스의 대답을 덧붙이자면.
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
좀 더 깨끗한...아마도?
이 대답이 이미 표시되었는지 확실하지 않습니다...
질문의 특정 패턴에 대해서는 한 번으로 수행할 수 있습니다.grep()
불러,
grep("A[169]", myfile$Letter)
사용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
공간을 제거합니다.다음과 같습니다.
matches <- unique(grep("A1|A9|A6", myfile$Letter, value=TRUE, fixed=TRUE))
다른 옵션은 다음과 같은 구문을 사용하는 것입니다.'\\b(A1|A9|A6)\\b'
본과 같이예를 들어 Bob이 "A7,A1"과 같은 문자를 가지고 있는 경우 해당 구문을 사용할 때 행을 추출할 수 있는 정규식 단어 경계입니다.다음은 두 옵션 모두에 대해 재현 가능한 예입니다.
df <- read.table(text="FirstName Letter
Alex A1
Alex A6
Alex A7
Bob A1
Chris A9
Chris A6", header = TRUE)
df
#> FirstName Letter
#> 1 Alex A1
#> 2 Alex A6
#> 3 Alex A7
#> 4 Bob A1
#> 5 Chris A9
#> 6 Chris A6
with(df, df[grep('\\b(A1|A9|A6)\\b', Letter),])
#> FirstName Letter
#> 1 Alex A1
#> 2 Alex A6
#> 4 Bob A1
#> 5 Chris A9
#> 6 Chris A6
df2 <- read.table(text="FirstName Letter
Alex A1
Alex A6
Alex A7,A1
Bob A1
Chris A9
Chris A6", header = TRUE)
df2
#> FirstName Letter
#> 1 Alex A1
#> 2 Alex A6
#> 3 Alex A7,A1
#> 4 Bob A1
#> 5 Chris A9
#> 6 Chris A6
with(df2, df2[grep('A1|A9|A6', Letter),])
#> FirstName Letter
#> 1 Alex A1
#> 2 Alex A6
#> 3 Alex A7,A1
#> 4 Bob A1
#> 5 Chris A9
#> 6 Chris A6
reprex 패키지(v2.0.1)에 의해 2022-07-16에 생성되었습니다.
참고: Rv4.1+를 사용하는 경우 다음을 사용할 수 있습니다.\\b
다른 용도로.\b
.
나는 Grep와 함께 스크립트를 조금 작성하고 여러 검색을 하는 것을 제안합니다.저는 여러 패턴을 검색할 수 있는 방법을 찾은 적이 없습니다. 그리고 저를 믿으세요, 저는 찾아봤습니다!
마찬가지로 문자열이 포함된 셸 파일:
#!/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";
그런 다음 myshell.sh 을 입력하여 실행합니다.
명령줄에서 문자열을 전달하려면 셸 인수(bash notation btw)를 사용하여 다음과 같이 수행합니다.
#!/bin/bash
$stingtomatch = "${1}";
grep *A6* "${stingtomatch}";
grep *A7* "${stingtomatch}";
grep *A8* "${stingtomatch}";
등등.
매치할 패턴이 많다면 for 루프에 넣을 수 있습니다.
언급URL : https://stackoverflow.com/questions/7597559/grep-using-a-character-vector-with-multiple-patterns
'bestsource' 카테고리의 다른 글
Firestore 하위 수집 대 어레이 (0) | 2023.06.18 |
---|---|
파생 클래스 속성 값이 기본 클래스 생성자에 표시되지 않는 이유는 무엇입니까? (0) | 2023.06.18 |
Wordpress 이미지 업로드에 연결 (0) | 2023.06.18 |
당신은 TypeScript에서 기능을 확장할 수 있습니까? (0) | 2023.06.18 |
Wordpress customizer 사용자 지정 제어 전송 postMessage가 작동하지 않음 (0) | 2023.06.18 |