반응형

/*********************************************************************************************************
-- Title : [R3.3] Dataframe - 조회 조건 및 피벗, 언피벗, 집계 추가
-- Reference : hrd-net
-- Key word : R dataframe data frame 데이터프레임 select where pivot unpivot dplyr tbl_df filter reshape2
                  arrange dcast cbind rbind melt 데이터 프레임 피벗 언피벗 arrange select 
*********************************************************************************************************/

-- R

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
   
# ********************************************
# -- dplyr 패키지 활용
#    DB에서 select ~ where와 유사
# ********************************************
 
# -- dplyr 패키지와 데이터 셋 hflight 설치
install.packages(c("dplyr""hflights"))
library(dplyr)                                        # 함수 사용 
library(hflights)                                     # dataset 사용  
 
# -- 차원 보기
dim(hflights) # 227496     21
head(hflights)
 
# -- tbl_df() 함수 : 데이터셋 화면창 안에서 한 눈에 파악할 수 있는 데이터 구성
hflights
hflights_df = tbl_df(hflights)
hflights_df
 
# -- filter(dataframe, 조건1,조건2)함수를 이용한 데이터 추출
filter(hflights_df, Month == 1, DayofMonth == 1)      # 1월 1일 데이터 추출
filter(hflights_df, Month == 1 | Month == 2)          # 1월 혹은 2월 데이터 추출
 
# -- arrange()함수를 이용한 정렬(년도,월,도착시간)
arrange(hflights_df, Year, Month, ArrTime )           # 오름차순 
 
# -- Month 기준 내림차순 정렬 - desc(변수)
arrange(hflights_df, desc(Month))
 
# -- select()함수를 이용한 열 조작
select(hflights_df, Year, Month, DayOfWeek)           # 3개 칼럼 선택
 
# -- 칼럼의 범위 지정 : Year~DayOfWeek 선택
select(hflights_df, Year:DayOfWeek)
 
# -- 칼럼의 범위 제외 : Year부터 DayOfWeek 제외
select(hflights_df, -(Year:DayOfWeek))
 
 
# ********************************************
# -- reshape2 패키지 활용
#    DB에서 pivot/unpivot와 grouping set과 유사 
# ********************************************
install.packages('reshape2')
library(reshape2)
 
# -- dcast()함수 이용 : 긴 형식 -> 넓은 형식 변경
#    '긴 형식'(Long format)을 '넓은 형식'(wide format)으로 모양 변경
 
data = read.csv("c:\\Rwork\\Part-II\\data.csv")
head(data)
 
# data.csv 데이터 셋 구성 - 22개 관측치, 3개 변수
# Date     : 구매날짜
# Customer : 고객ID
# Buy      : 구매수량
 
# -- '넓은 형식'(wide format)으로 변형
#    형식) dcast(데이터셋, 앞변수~뒤변수, 함수)
#          앞변수 : 행 구성, 뒷변수 : 칼럼 구성
 
wide = dcast(data, Customer_ID ~ Date, sum)
wide 
 
 
# -- 열 또는 행 단위 통계치 계산 함수 
#    colSums(), rowSums(), colMeans(), rowMeans()
 
# -- 고객별,날짜별 구매횟수의 합계 구하기
rowSums(wide)                                         # 행 합계 -> 고객별
colSums(wide)                                         # 열 합계 -> 날짜별
 
# -- cbind와 rbind() 이용하여 원래 데이터 셋에 붙임 
wide = cbind(wide, rowSums(wide))                     # 컬럼으로 행 합계 붙임
wide = rbind(wide, colSums(wide))                     # 행으로 컬럼 합계 붙임
wide
 
# -- 컬럼명 변경 : 'Sum by User' 
colnames(wide)
colnames(wide)[9= 'Sum by User' # 9번째 컬럼명 변경
 
# -- 특정 셀값 변경 : 'Sum by day'
wide[6,1= 'Sum by day'
wide
 
 
# -- melt() 함수 이용 : 넓은 형식 -> 긴 형식 변경
#    형식) melt(데이터셋, id='열이름 변수')
 
wide = wide[-6,-9# 6행과 9컬럼 제거
wide
 
# -- 긴 형식 변경
#    id변수를 기준으로 넓은 형식이 긴 형식으로 변경
long = melt(wide, id='Customer_ID'
long
 
# -- 칼럼명 수정.
name = c("Customer_ID""Date""Buy")
colnames(long) = name   
head(long)
 
# reshape2 dataset
data("smiths")
smiths 
 
# wide -> long
long = melt(id=1:2, smiths)                           # id:기준 칼럼 
long
 
# long -> wide
wide = dcast(long, subject + time~...)
wide
 

cs


-- Files

data.csv



반응형

+ Recent posts