2017-02-05 7 views
0

문자열 목록에서 부분 일치를 데이터 프레임에 적용하는 데 문제가 있습니다.R 부분 일치 문자열

내 DF는이 구조가 있습니다

> df 
    mrun          address stat 
8988741 cerro pedregal 8536 , Antofagasta, Antofagasta OK 
17625851    rancagua 2777 , Iquique, Tarapacá OK 
9423953    picarte 4100 , Valdivia, Los Ríos OK 
3459140   balmaceda 935 , Temuco, La Araucanía OK 
24507700    rancagua 1940, La Serena, Coquimbo OK 

을하고 나는이 값을 문자열 목록이 있습니다

> address_list 
c("balmaceda", "rancagua", "bombero garrido") 

이 어떻게 목록에있는 모든 요소와 일치하는 것보다 행을 선택할 수 있습니다 ?


이 내 욕망의 출력 :

> df_solution 
    mrun          address stat 
17625851    rancagua 2777 , Iquique, Tarapacá OK 
3459140   balmaceda 935 , Temuco, La Araucanía OK 
24507700    rancagua 1940, La Serena, Coquimbo OK 

편집 : saurav의 shekhar에 의해 주어진 솔루션은 몇 가지 요소가 포함 된 ADDRESS_LIST 작동합니다. 내 경우에는, 내 진짜 ADDRESS_LIST 5000 행 이상 가지고 있으며, DF 200000 개 행이 grep은이 오류가 발생합니다 : 나는 그것에 대해 생각하지 않도록

> df$flag[grep(address_list,df$address)]<- 1 
Error in grep(address_list,df$address) : 
    invalid regular expression, reason 'Out of memory' 

내가 RAM을 많이 가지고 있어요. 솔루션을 찾았지만 어떤 방법으로도 찾지 못했습니다. SO의 유일한 가까운 스레드는 this link이지만 내 경우에 적용하는 방법을 알지 못했습니다.

내 세션 정보 : 당신이해야 할

> sessionInfo() 
R version 3.3.2 (2016-10-31) 
Platform: x86_64-w64-mingw32/x64 (64-bit) 
Running under: Windows >= 8 x64 (build 9200) 

locale: 
[1] LC_COLLATE=Spanish_Latin America.1252 LC_CTYPE=Spanish_Latin America.1252 
[3] LC_MONETARY=Spanish_Latin America.1252 LC_NUMERIC=C       
[5] LC_TIME=Spanish_Latin America.1252  

attached base packages: 
[1] stats  graphics grDevices utils  datasets methods base  

other attached packages: 
[1] gridExtra_2.2.1 ggplot2_2.2.0 plyr_1.8.4  reshape_0.8.6 

답변

0

우선은 다음과 같은 형식의 변수를 일치 만드는 것입니다 :

address_list<- paste(address_list, collapse = ",") 
address_list<- gsub("," , "|" , address_list) 
address_list<- c("balmaceda|rancagua|bombero|garrido") 

그런 다음 당신은 당신의 데이터에 대한 부분 검색을 할 수 grep를 사용하여 유지할 행에 대한 플래그를 작성하십시오.

# grep(address_list,df$address) Try this and note the output for your understanding of `grep` 

df$flag<- NA 
df$flag[grep(address_list,df$address)]<- 1 #flag rows with matching values 
df_new<- df[which(df$flag==1),] 
+0

몇 분 후에 이것을 시도해 보겠습니다. 그건 그렇고, 내 address_list 1500 값이 있습니다. 목록에서 파이프로이 모든 값을 분리 할 수 ​​있습니까? –

+0

"bombero garrido"는 하나의 문자열이므로 df $ adrress의 값은 "bombero garrido 23345, Valdivia, los ríos", "bombero garrido 138, Antofagasta, Antofagasta"등이 될 수 있습니다. bombero garrido ". –

+0

두 번째 의견에 - 텍스트를 별도로 유지할지 또는 함께 사용해야하는지 여부. 그래도 문제가 있다면 알려주세요 –