>RE::VISION CRM

R 데이터 분석

[R분석] 장바구니 분석

YONG_X 2015. 5. 12. 17:31


# 전용준 :: 리비젼컨설팅 :: 02-415-7650 :: revision.co.kr :: xyxonxyxon@empal.com

#==================================================



최초 예제 소스 : http://www.salemmarafi.com/code/market-basket-analysis-with-r/


# Load the libraries

library(arules)

library(arulesViz)

library(datasets)

 

# Load the data set


# 만일 기본 제공되는 데이터 셋을 바로 활용하고자 하는 경우

# data(Groceries)


# 임의의 데이터 셋을 활용하기 위해 로딩하는 예

# -------------------------

k01 <- read.transactions("C:/Users/revision/Desktop/rvc_kb/02_EnGageMent/000_011_lawmakers/Groceries.csv",rm.duplicates=T, format="basket",  sep="," );


inspect(head(k01, 5))


# Groceries  데이터 셋의 모습은 컴마로 구분되어 옆으로 펼쳐진 영수증 모습 (2차원 테이블에 리스트 형식)





# Create an item frequency plot for the top 20 items

itemFrequencyPlot(k01,topN=20,type="absolute")



# Get the rules

rules <- apriori(Groceries, parameter = list(supp = 0.005, conf = 0.4, minlen=2, maxlen=2))

# minlen과 maxlen이 모두 2로 지정되어 있기에 lefthand side 에 하나의 아이템으로만 도출

 

# Show the top 5 rules, but only 3 digits

# digits는 소수점 자릿수


options(digits=3)

inspect(rules[1:10])


# 아래는 결과

#-----------------


   lhs                      rhs                support confidence lift

1  {cake bar}            => {whole milk}       0.00559      0.423 1.66

2  {mustard}             => {whole milk}       0.00519      0.432 1.69

3  {pot plants}          => {whole milk}       0.00691      0.400 1.57

4  {pasta}               => {whole milk}       0.00610      0.405 1.59

5  {herbs}               => {root vegetables}  0.00702      0.431 3.96

6  {herbs}               => {other vegetables} 0.00773      0.475 2.45

7  {herbs}               => {whole milk}       0.00773      0.475 1.86

8  {processed cheese}    => {whole milk}       0.00702      0.423 1.66

9  {semi-finished bread} => {whole milk}       0.00712      0.402 1.57

10 {detergent}           => {whole milk}       0.00895      0.466 1.82




summary(rules)


# 생성된 Rule의 수가 너무 많으면 support, confidence option을 조정해서 다시 생성 반복 


# sorting stuff out

# confidence, support, lift로도 sort 가능

rules<-sort(rules, by="lift", decreasing=TRUE)

inspect(head(sort(rules, by="confidence"), 30))


# Visualization

# library(arulesViz)

# 별도의 창이 팝업되며, 옵션을 조절하면 화면크기에 맞도록 보이게 할 수 있음


plot(rules, method="graph", interactive=TRUE, shading=NA)



# 결과로 이 형태의 팝업창이 뜨면 정상. 창의 사이즈 조절후 Fit to Screen 메뉴 사용