R의 grep()과 grepl() 비교: 차이점은 무엇입니까?
사람들이 R에서 자주 혼동하는 두 가지 기능은 grep() 및 grepl() 입니다. 두 함수 모두 문자열에 특정 패턴이 있는지 확인할 수 있지만 서로 다른 결과를 반환합니다.
- grepl()은 문자열에 패턴이 있으면 TRUE를 반환합니다.
- grep()은 패턴을 포함하는 문자열 인덱스의 벡터를 반환합니다.
다음 예에서는 이러한 차이점을 보여줍니다.
#create a vector of data data <- c('P Guard', 'S Guard', 'S Forward', 'P Forward', 'Center') grep ('Guard', data) [1] 1 2 grepl ('Guard', data) [1] TRUE TRUE FALSE FALSE FALSE
다음 예에서는 이러한 기능 중 하나를 다른 기능보다 먼저 사용하려는 경우를 보여줍니다.
grepl()을 사용하는 경우
1. 특정 문자열이 포함된 행 필터링
grepl() 의 가장 일반적인 용도 중 하나는 특정 문자열이 포함된 데이터 프레임의 행을 필터링하는 것입니다.
library(dplyr) #create data frame df <- data.frame(player = c('P Guard', 'S Guard', 'S Forward', 'P Forward', 'Center'), points = c(12, 15, 19, 22, 32), rebounds = c(5, 7, 7, 12, 11)) #filter rows that contain the string 'Guard' in the player column df %>% filter( grepl ('Guard', player)) player points rebounds 1 P Guard 12 5 2 S Guard 15 7
관련 항목: dplyr을 사용하여 특정 문자열이 포함된 행을 필터링하는 방법
grep()을 사용하는 경우
1. 특정 문자열이 포함된 열을 선택합니다.
grep()을 사용하여 특정 문자열이 포함된 데이터 프레임의 열을 선택할 수 있습니다.
library(dplyr) #create data frame df <- data.frame(player = c('P Guard', 'S Guard', 'S Forward', 'P Forward', 'Center'), points = c(12, 15, 19, 22, 32), rebounds = c(5, 7, 7, 12, 11)) #select columns that contain the string 'p' in their name df %>% select( grep ('p', colnames(df))) player points 1 P Guard 12 2 S Guard 15 3S Forward 19 4P Forward 22 5 Center 32
2. 특정 문자열이 포함된 줄 수 계산
grep()을 사용하여 특정 문자열을 포함하는 데이터 프레임의 줄 수를 계산할 수 있습니다.
#create data frame df <- data.frame(player = c('P Guard', 'S Guard', 'S Forward', 'P Forward', 'Center'), points = c(12, 15, 19, 22, 32), rebounds = c(5, 7, 7, 12, 11)) #count how many rows contain the string 'Guard' in the player column length( grep ('Guard', df$player)) [1] 2
여기에서 더 많은 R 튜토리얼을 찾을 수 있습니다.