IT기술/BigData

R 활용 예제 실습

dobbby 2014. 2. 14. 10:38
반응형

#step1. 작업용 디렉터리를 지정

setwd("D:/yul/temp")


#step2. 필요패키지 설치 후 R에 loading

install.packages("KoNLP") # 한국어 작업시 필요한 패키지

install.packages("wordcloud") # wordcloud 작업 패키지


library(KoNLP)

library(wordcloud)

useSejongDic() # 한글이 저장되어 있는 세종사전을 사용함


#step3. 분석용 데이터를 변수로 읽기

f <- file("big.txt", blocking=F) # 분석용 데이터가 저장된 파일

txt <- readLines(f) # txt  라는 변수에 한줄씩 읽어들임


#step4. 데이터 중 명사만 골라낸 후 nouns 변수에 할당

nouns <- sapply(txt, extractNoun, USE.NAMES=F)


#step5. 추출된 명사를 상위 20개만 출력해서 확인

head(unlist(nouns), 20)


#step6. 파일에 저장해 둠 (선택사항)

write(unlist(nouns), "big_2.txt")


#step7. 수정 완료된 파일을 다시 변수에 불러들임

rev <- read.table("big_2.txt")


#step8. 화면에 그래픽으로 출력하기 전에 text 형태로 결과 확인

nrow(rev)

wordcount <- table(rev)

length(wordcount)

head(sort(wordcount, decreasing=T), 20)


#step9. Word Cloud 형태로 그래픽 출력

# color=set, rotation percent=0.25

library(RColorBrewer) # 화면에 출력할 컬러를 사용할 라이브러리를 Loading

palete <- brewer.pal(9,"set1") # 글자색을 지정

x11() # 그래픽 창 생성

wordcloud(names(wordcount),freq=wordcount,scale=c(5,1),rot.per=0.25,min.freq=5,random.order=F,random.color=T,color=palete)

# min.freq 항목은 최소 5회 이상 언급된 단어만 출력하라는 예


#step10. 원하지 않는 내용 걸러내기

txt <- gsub("\\n","", txt) # new line 문자 없애기

txt <- gsub("\\d+", "", txt) # 모든 숫자 없애기

txt <- gsub("빅데이터", "", txt)

txt <- gsub("빅", "", txt)

txt <- gsub("데이터", "", txt)

txt <- gsub("언론사", "", txt)

txt <- gsub("관련기사", "", txt)

txt <- gsub("네이버에서", "", txt)

txt <- gsub("검색", "", txt)

txt <- gsub("보내기", "", txt)

txt <- gsub("내", "", txt)

txt <- gsub("일전", "", txt)

txt <- gsub("한", "", txt)

txt <- gsub("해", "", txt)

txt <- gsub("의", "", txt)

txt <- gsub("를", "", txt)

txt <- gsub("적", "", txt)

txt <- gsub("엣", "", txt)

txt <- gsub("들", "", txt)

txt <- gsub("일", "", txt)

# 위 작업 후 step4 부터 다시 합니다.


#step11. 다시 Word Cloud 형태로 출력

# color=set1, rotation percent=0

palete <- brewer.pal(9, "Set1")

x11()

wordcloud(names(wordcount),freq=wordcount,scale=c(5,1),rot.per=0.10,min.freq=5,random.order=F,random.color=T,colors=palete)


#step12. 원하는 결과가 나왔으면 그림 파일로 저장

savePlot("big.png", type="png")

# end




반응형