이경수 선생님의 수학실험실

R function_example3 본문

R

R function_example3

(이경수) 2021. 4. 20. 17:29

다음은 문서에 사용된 단어와 그 단어가 쓰이는 위치를 모두 검색하는 함수에 대한 소개입니다. 문서자료 'poisson.txt'는 wikipedia에서 포아송 분포를 검색했을 때의 내용을 사용하였습니다.

 

 

scan( )로 txt file의 내용을 읽어 보면, 다음과 같이 출력됩니다. (절대경로 또는 상대경로)

> txt <- scan("C:/Users/user/Desktop/poisson.txt","")
Read 188 items
> txt
  [1] "In"                               "probability"                     
  [3] "theory"                           "and"                             
  [5] "statistics,"                      "the"                             
  [7] "Poisson"                          "distribution"                    
  [9] "(/<cb>늩w<c9>뫫릗<c9>뭤/;"        "French"                          
 [11] "pronunciation:"                   "<e2>\u0080<8b>[pwas<c9>붛<83>]),"
 [13] "named"                            "after"                           
 [15] "French"                           "mathematician"                   
 [17] "Sim챕on"                          "Denis"                           
 [19] "Poisson,"                         "is"                              
 [21] "a"                                "discrete"                        
 [23] "probability"                      "distribution"                    
 [25] "that"                             "expresses"                       
 [27] "the"                              "probability"                     
 [29] "of"                               "a"                               
 [31] "given"                            "number"                          
 [33] "of"                               "events"                          
 [35] "occurring"                        "in"                              
 [37] "a"                                "fixed"                           
 [39] "interval"                         "of"                              
 [41] "time"                             "or"                              
 [43] "space"                            "if"                     

 

findwords() 함수를 정의하여 wlist에 각 단어의 순서가 담겨있는 벡터를 저장합니다.

> findwords <- function(x){
+     txt <- scan(x, "")
+     wlist <- list()
+     for(i in 1:length(txt)){
+         word <- txt[i]
+         wlist[[word]] <- c(wlist[[word]], i)
+     }
+     return(wlist)
+ }
> findwords("poisson.txt")
Read 188 items
$In
[1] 1

$probability
[1]   2  23  28 112 131 153 165

$theory
[1] 3

$and
[1]   4  54 139 143 148 161

$`statistics,`
[1] 5

$the
[1]   6  27  57  60  71 111 115 133 173

$Poisson
[1]   7  64 130

 

 

'R' 카테고리의 다른 글

R Text mining  (0) 2021.04.21
R List indexing  (0) 2021.04.21
R function_example2  (0) 2021.04.20
R function_example1  (0) 2021.04.20
R의 데이터 타입_배열(array)  (0) 2021.04.20
Comments