R 대시보드
- flexdashboard 를 이용하면
R로 유연하고 (flexible), 매력적이며(attractive), 쌍방향의(Interactive)
대시보드를 쉽게(easily) 만들 수 있음.
- 대시보드 작성 및 커스터마이제이션은 Rmarkdown에 기반하여 이루어지며, Shiny 컴포넌트들도 덧붙일 수 도 있다.
- 이외에도 htmlwidgets, base/lattice/grid 그래픽, tabula(표) 데이터, 주석 같은 다양한 컴포넌트들까지도 지원하며,
열과 행 기반 레이아웃, 스토리보드 등이 제공된다는 장점도 가지고 있음
2. flexdashboard 시작하기
flexdashboard 는 R의 패키지이므로, 설치는 R의 여타 패키지처럼 설치
- 쉼표로 여러개 한번에 설치 가능
대표사진 삭제
사진 설명을 입력하세요.
---
title: "Dashboard Example"
output: # 출력 결과에 대한 환경 설정(아랫줄들을 붙여쓰면 안된다, 전체적인 위치는 columns 구조 )
flexdashboard::flex_dashboard:
orientation: columns # 기본위치값이 열단위로 만들어진다는 의미(columns, rows 선택 가능)
vertical_layout: scroll # 가로 사이즈를 flexdashboard 사이즈에 맞춰서 꽉 채우라는 의미(fill, scroll 선택 가능)
---
```{r setup, include=FALSE}
# 청크코드의 이름은 setup으로 지정, include는 안시키겠다.(문서 만들때만 잠깐 사용)
library(flexdashboard)
library(ggplot2) #해당 라이브러리를 계속 사용하면 여기에 써놓고, 한번만 사용할거면 청크코드에 쓰면 된다.
```
Column {data-width=650}
-----------------------------------------------------------------------
<!-- 첫 번째 컬럼 가로크기를 650(이 내부에 들어가는 것은 컬럼으로 만들겠다.라고 선언(Column 대소문자 구분)) -->
### Chart A
```{r}
ggplot(data=mtcars, aes(x=hp, y=mpg, color=as.factor(cyl)))+
geom_point()
```
Column {.tabset .tabset-fade}
-----------------------------------------------------------------------
<!-- 두 번째 컬럼 가로크기를 350 -->
<!-- .tabset은 탭을 나눠주는 방법, fade는 전환시 부드러운 효과 -->
### Chart B
```{r}
ggplot(data=mtcars)+
geom_bar(mapping=aes(x=cyl, fill=as.factor(am)))
```
### Chart C
```{r}
ggplot(data=mtcars)+
geom_bar(mapping = aes(x=cyl, fill=as.factor(cyl)), position="dodge")+
coord_polar() # 나이팅게일 함수 같은 방사형 차트 표시해주는 함수
```
전송중...
사진 설명을 입력하세요.
---
title: "Untitled"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: scroll
---
```{r setup, include=FALSE}
#https://rmarkdown.rstudio.com/flexdashboard/using.html#compenents
#html widgets의 최대 단점이 데이터셋을 모두 임베디드한다.(얘를 쓰면 모든 데이터를 다 가져오게 되어서 용량에서 손해)
library(flexdashboard)
library(dygraphs) # 시계열 자료에 대한 시각화 그래프 구현할 때, 하이라이트, 줌 등의 기능을 제공한다.
library(plotly) # ggplot2를 인터랙티브한 웹 버전으로 변환해주는 패키지
#install.packages("highcharter")
library(highcharter)
```
### Lung Deaths (All)
```{r}
dygraph(ldeaths)
```
### Lung Deaths (Male)
```{r}
dygraph(mdeaths)
```
### Lung Deathhs (Female)
```{r}
dygraph(fdeaths)
```
### Lung Deaths (all, plotly)
```{r}
plot_ly(mtcars, x=~hp, y=~mpg, type='scatter', mode='markers', color=~as.factor(cyl))
```
### Lung Deaths (Male, hchart)
```{r}
hchart(mtcars, "scatter", hcaes(x=hp, y=mpg, group = as.factor(cyl)))
```
### Lung Deaths (Female, hchart)
```{r}
hchart(diamonds$price, color="#B71C1C", name="Price") %>%
hc_title(text = "You can Zoom me")
```
전송중...
사진 설명을 입력하세요.
---
title: "Figure Sizes"
output:
flexdashboard::flex_dashboard:
orientation: columns
vertical_layout: scroll
runtime: shiny
---
```{r setup, include=FALSE}
library(flexdashboard)
```
Column
-----------------------------------------------------------------------
# Chart
### Chart 1 (12, 7) 비율(크기아님)
```{r, fig.width=12, fig.height=7}
plot(cars)
```
### Chart 2 (5, 5)
```{r, fig.width=5, fig.height=5}
plot(pressure)
```
### Chart 3 (10, 7)
```{r, fig.width=10, fig.height=7}
plot(airmiles)
```
# Table
### Chart 5 (10, 7)
```{r}
library(shiny)
renderTable({ #10개 데이터만 표로 만들어서 출력하기
head(mtcars, 10)
})
```
```{r}
DT::datatable(mtcars,
options = list(pageLength=25,
bPaginate=T),
filter="top")
```
전송중...
사진 설명을 입력하세요.
---
title: "Guage, navigation Bar & text Annotation"
output:
flexdashboard::flex_dashboard:
orientation: columns
source_code: embed
navbar:
- { title: "About", href: "https://www.naver.com/",align: right } # 글자로하려면 타이틀
- { icon: "fa-pencil", href: "https://www.github.com/",align: right} # 그림으로 하려면 아이콘 속성
---
```{r setup, include=FALSE}
library(flexdashboard)
library(ggplot2)
library(knitr)
```
Row1
-----------------------------------------------------------------------
### valuebox Example1
```{r}
valueBox(42,
icon = "fa-github")
```
### # of Bit Coin
```{r}
num = 8
valueBox(num,
icon = "fa-bitcoin",
color = "info")
```
### valuebox Example3
```{r}
num = 50
valueBox(num,
caption="APPLE PAY",
icon = "fa-bluetooth",
color = ifelse(num>10, "warning", "primary")) # 워닝,프라이머리는 내장 상수(값을 10 미만으로 하면 색이 바뀜)
```
### valuebox Example4
```{r}
valueBox(107,
caption="AWS",
icon = "fa-cannabis",
color = "success")
```
Row2
-----------------------------------
### ggplot2 graph
```{r}
ggplot(data=mtcars)+
geom_bar(mapping = aes(x=cyl, fill=as.factor(am)),
position="dodge")+
theme(legend.position = "blank")
```
### Tabular data
```{r}
kable(mtcars)
```
전송중...
사진 설명을 입력하세요.
---
title: "Guage, navigation Bar & text Annotation"
output:
flexdashboard::flex_dashboard:
orientation: columns
source_code: embed
navbar:
- { title: "About", href: "https://www.naver.com/",align: right }
- { icon: "fa-pencil", href: "https://www.github.com/",align: right}
---
<!-- # 글자로하려면 타이틀 # 그림으로 하려면 아이콘 속성 -->
```{r setup, include=FALSE}
library(flexdashboard)
library(ggplot2)
library(knitr)
```
Column 1
-----------------------------------------------------------------------
### Gauge ex1. Contact Rate
```{r}
gauge(45, min=0, max=100, symbol = '%', #전달되는 값에 따라서 색상을 변경시키라는 의미
sectors = gaugeSectors(success = c(80, 100),
warning = c(40, 79),
danger = c(0, 39)))
```
### Gauge ex2. Average Rating
```{r}
rating=42
gauge(rating, 0, 50, label = 'Test', gaugeSectors(
success = c(41, 50), warning = c(21, 40), danger = c(0, 20)))
```
전송중...
사진 설명을 입력하세요.
전송중...
사진 설명을 입력하세요.
---
title: "Multiple Pages"
output:
flexdashboard::flex_dashboard:
orientation: columns
source_code: embed
navbar:
- { title: "About", href: "https://www.naver.com/",align: right }
- { icon: "fa-pencil", href: "https://www.github.com/",align: right}
---
Pag1 1
==========================================
This is an example. As you can see, flexdashboard can have text annotations.
```{r setup, include=FALSE}
library(flexdashboard)
library(ggplot2)
library(knitr)
```
Column 1
-----------------------------------------------------------------------
### Gauge ex1. Contact Rate
```{r}
gauge(45, min=0, max=100, symbol = '%', #전달되는 값에 따라서 색상을 변경시키라는 의미
sectors = gaugeSectors(success = c(80, 100),
warning = c(40, 79),
danger = c(0, 39)))
```
### Gauge ex2. Average Rating
```{r}
rating=42
gauge(rating, 0, 50, label = 'Test', gaugeSectors(
success = c(41, 50), warning = c(21, 40), danger = c(0, 20)))
```
### Text Annotation
One of the dashboard section can be as a text area.
Markdown Grammers can be helpful here.
It is not that difficult.
Just have a try
Column 2
-----------------------------------------------------------------------
Page2 {data-orientation=rows}
==================================================
### ggplot2 chart1
```{r}
ggplot(data=mtcars, aes(x=hp, y=mpg, color=as.factor(cyl)))+
geom_point() +
theme(legend.position = "blank")
```
#########################################################
#서점의 고객 데이터에 대한 가상 사례
#--> 타겟팅을 누구를 잡을건지?, 마케팅 대상을 누구를 잡아서 할건지?
#탐색적인 분석과 고객세분화 응용 사례
#########################################################
#작업 파일 : cust_seg_smpl_280122.csv
cs0 <- read.csv("C:/rStudy/1stRreport/cust_seg_smpl_280122.csv")
head(cs0)
전송중...
사진 설명을 입력하세요.
names(cs0)
전송중...
사진 설명을 입력하세요.
cs1 <- cs0
names(cs1) <- c("cust_name", "sex", "age", "location", "days_purchase",
"recency", "num_books", "amt_books", "amt_non_book",
"amt_total", "interest_genre", "num_genre",
"membership_period", "sms_optin")
names(cs1) # 바뀐 컬럼명 확인
전송중...
사진 설명을 입력하세요.
# --------------------------------------------------------
#작업 내용
# --------------------------------------------------------
#########################################################
#최종구매후기간 recency와 구매한 서적의 수간의 관계 확인
plot(cs1$recency, cs1$num_books)
전송중...
사진 설명을 입력하세요.
#동일 좌표에 다수의 고객 존재 가능성이 있으므로 jitter 활용
# --------------------------------------------------------
# jitter()
# jitter는 데이터 값을 조금씩 움직여서 같은 점에 데이터가 여러번 겹쳐서 표시되는 현상을 막는다.
# --------------------------------------------------------
# Description
#숫자 벡터에 소량의 노이즈를 추가하는 함수
#Usage
#jitter(x, factor=1, amount=NULL)
#Arguments
# x: 지터를 추가 할 숫자 형 벡터.
#
# factor : numeric(숫자).
# amount : numeric(숫자).
#양수이면 양으로 사용되며
#그렇지 않으면 =0
#기본값은 facor * z /50 입니다.
# amount의 기본값은 NULL
# factor * d /5 여기서 d는 x값 사이의 가장 작은 차이
# --------------------------------------------------------
#Examples
#z <- max(x)-min(x) 라고 하자(일반적인 경우를 가정).
#추가 될 양 a는
#다음과 같이 양의 인수 양으로 제공되거나 z에서 계산된다.
#만약 amount == 0 이면 a <- factor * z/50 을 설정.
round(jitter(c(rep(1,3),rep(1.2,4),rep(3,3))),3) # 소수점 이하 3자리부터 round 시킨다.
전송중...
사진 설명을 입력하세요.
########################################################### 가설 1단계 : 구매한지 오래될 수록 구매 서적 수가 많음
plot(jitter(cs1$recency), jitter(cs1$num_books))
전송중...
사진 설명을 입력하세요.
abline(lm(cs1$num_books~cs1$recency),col="blue")
전송중...
사진 설명을 입력하세요.
# 1차 가설에 대한 해석
## 회귀선과 보조선을 그려 본 결과
## 책을 구매한 지 오래된 사람이 구매한 책의 수량이 더 많다.(구매한지 얼마 안 된 사람들이 구매한 수량이 더 적다.(인원은 더 많다.))
## 이 그래프를 확인해 보았을 때, 우리는
# 최근에 구매한 사람들을 관리대상으로 지정해야 함을 알 수 있다.
########################################################### 가설 2단계 : 비싼 책을 샀는지에 대한 평균 금액 계산
#
#엑셀에서 천단위 comma가 포함된 것을 gsub 함수로 제거
cs1$amt_books <- as.numeric(gsub(",",
"",
as.character(cs1$amt_books))
)
cs1$amt_non_book <- as.numeric(gsub(",",
"",
as.character(cs1$amt_non_book))
)
plot(jitter(cs1$num_books), jitter(cs1$amt_books))
abline(lm(cs1$amt_books~cs1$num_books),
col="blue")
전송중...
사진 설명을 입력하세요.
# 2차 가설에 대한 해석
## 구매량이 적은 사람들의 구매금액이 적고, 구매량이 많은 사람들의 구매금액이 큰 것을 확인할 수 있다.
## 보조선을 그려봄에 따라, 구매수량에 비례해서 금액이 커지는 것을 확인할 수 있음.
cs1$unitprice_book <- cs1$amt_books / cs1$num_books
plot(jitter(cs1$num_books),
jitter(cs1$unitprice_book),
pch=19,
col="blue",
cex=0.7,
ylim=c(0, max(cs1$unitprice_book)*1.05)
)
abline(lm(cs1$unitprice_book~cs1$num_books),
col="blue",
lwd=2, lty=2)
abline(h=median(cs1$unitprice_book),
col="darkgrey")
전송중...
사진 설명을 입력하세요.
## --> 구매량이 적더라도 비싼책을 샀는지, 구매량이 많더라도 저렴한 책만 많이 샀는지 확인할 수 있다.
## 사업방향에 대한 계획 수립 가능
########################################################### 3단계 : 성별 별로 평균 구매금액이 어떤지 확인
#성별을 구분해서 특성 차이 비교
plot(jitter(cs1$num_books),
jitter(cs1$unitprice_book),
pch=19,
cex=0.7,
col=ifelse(cs1$sex=='여', "pink", "blue"),
ylim=c(0, max(cs1$unitprice_book)*1.05),
sub="pink: female blue:male")
abline(lm(cs1$unitprice_book~cs1$num_books),
col="blue",
lwd=2, lty=2)
abline(h=median(cs1$unitprice_book),
col="darkgrey")
전송중...
사진 설명을 입력하세요.
## 남성의 평균 구매가가 더 높은 것을 확인할 수 있다.
## --> 여성의 평구매가를 끌어올려야 한다 or 이미 검증된 남성의 소비심리를 더 자극하여야 한다.
## 둘 중 어느 방향으로 계획을 수립해야 할 지 선택해야 한다.
plot(jitter(cs1$num_books),
jitter(cs1$unitprice_book),
pch=19,
cex=4*cs1$amt_books/max(cs1$amt_non_book),
col=ifelse(cs1$sex=='여', "pink", "blue"),
ylim=c(0, max(cs1$unitprice_book)*1.05),
sub="size: 서적이외 상품 구매액"
)
abline(lm(cs1$unitprice_book~cs1$num_books),
col="blue",
lwd=2, lty=2)
abline(h=median(cs1$unitprice_book),
col="darkgrey")
전송중...
사진 설명을 입력하세요.
## 이상치를 제외하고 확인했을 때, 책을 많이 살 수록 서적 외 다른 상품들도 많이 구매함을 알 수 있다.
## --> 서적에 대한 구매력을 올려야 한다. or 기타 주력상품을 카테고리화 하여 판매량에 대한 분석을 할 수 있다.(캐시카우 확인, 문제아 확인)
'PYTHON' 카테고리의 다른 글
20200410 - R 파이썬 함수, 클래스, 파일다루기, 실전 프로젝트, 파이썬과 COM (0) | 2020.04.10 |
---|---|
20200409 - Python 파이썬 소개, 기본문법, 연습문제, 예제파일, (시험) (0) | 2020.04.09 |
20200406 - R 파싱하여 데이터 가져오기, 웹 페이지 크롤링, 트리맵, 워드클라우드, 차트 (0) | 2020.04.06 |
20200403 - R, 텍스트 마이닝(형태소 분석, 품사 추출, 빈도표 만들기, 시각화) (0) | 2020.04.03 |
20200402 - R (데이터 전처리, 변수 간 관계 분석 - 직업별 월급 차이 ) (0) | 2020.04.02 |
댓글