# 20만건 이상의 데이터가 담긴 샘플 hflighrs 패키지 설치
# install.packages('hflights')
# 그림 라이브러리
library(ggplot2)
library(hflights)
# 구조 확인 - str()
str(hflights)
# 맨 앞 자로 확인(6개) - head()
head(hflights)
# 특정 변수 확인
dest_table <- table(hflights$Dest)
dest_table
# 명목형 변수 개수 확인 - lenght()
length(dest_table)
# 범위 확인 - range() : 최소값 최대값
range(dest_table)
# 가장 큰값, 작은값의 이름 찾기
dest_table[dest_table == 1]
dest_table[dest_table == 9820]
# dest가 5000이 넘는 테이블
dest_table_5000 <- dest_table[dest_table > 5000]
dest_table_5000
# 막대그래프 작성
barplot(dest_table_5000)
# 데이터 가져오기
df <- read.csv('r-ggagi-data/example_cancer.csv')
str(df)
# 연령대별 도수 - 연속형 변수, 구간 나누기
age_table <- table(cut(df$age, breaks=(0:11)*10))
age_table
# 변수 이름 변경
rownames(age_table) <- c('1s','10s','20s','30s','40s','50s','60s','70s','80s','90s','100s')
age_table
head(df,3)
# 시각화1 : 막대그래프
barplot(age_table)
# 시각화2 : 선
library('ggplot2')
library('ggthemes')
ggplot(data=df, aes(x=age)) +
geom_freqpoly(binwidth=10, size=1.4, colour='orange') +
theme_wsj()
# 데이터 로드
df <- read.csv('r-ggagi-data/example_coffee.csv', header = T, stringsAsFactors = T)
# 데이터 구조 확인
str(df)
# 불필요 변수 제거
df <- subset(df,
select=c(-adress, -adressBystreet, -dateOfclosure, -startdateOfcessation, -duedateOfcessation, -dateOfreOpen, -zip))
str(df)
# 최초 커피숍 찾기
range(df$yearOfStart) # 결과값 x
range(df$yearOfStart, na.rm = T) # 결측치 제거
# 1964년에 오픈한 최초의 커피숍
subset(df, subset = (yearOfStart == 1964))
# 가장 오래된 운영중인 커피숍 찾기
df_filter <- subset(df, subset = (stateOfbusiness == '운영중'))
range(df_filter$yearOfStart, na.rm = T) # 결측치 제거
subset(df_filter, subset = (yearOfStart == 1967))
# 해마다 오픈하는 커피숍 개수
table(df$yearOfStart)
# 시각화
qplot(data = df, df$yearOfStart, geom='bar') # geom : 차트의 모양
# 분할표 작성 - 운영중/폐업
stat_table <- table(df$stateOfbusiness, df$yearOfStart)
stat_table
# 조건으로 특정 칼럼값 찾기 - wihch()
# 행조건 rownames, 열조건 colnames
which(colnames(stat_table) == 1993) # = 칼럼명이 1993인 위치 찾기
which.max(colnames(stat_table)) # = 최대치 칼럼(마지막)의 위치
# 위에서 찾은 칼럼 위치(26~48)에 해당하는 테이블 생성
stat_table_col_26_48 <- stat_table[,c(26:48)]
stat_table_col_26_48
# 비율 계산
stat_prop_table <- prop.table(stat_table_col_26_48, margin = 2) # margin = 2 열기준
stat_prop_table
# 데이터프레임 구성
input1 <- stat_table_col_26_48
input2 <- stat_prop_table
df_bind <- data.frame(colnames(input1), input1[1,], input1[2,], input2[1,], input2[2,])
df_bind
# 행삭제, 열이름 부여
rownames(df_bind) <- NULL
colnames(df_bind) <- c('Year','Open','Close','POpen','PClose')
df_bind
# 시각화 - 선 / aes = 축
ggplot(df_bind, aes(x=Year, y=Close, group=1)) +
geom_line(colour='steelblue1', size=1) +
geom_point(colour='steelblue', size=3) +
geom_line(aes(y=Open), colour='tomato2', size=1) + # aex를 따로 지정하지 않으면 선행된 Year, Close가 사용
geom_point(aes(y=Open), colour='red', size=3) +
theme_bw() # 배경 색
# 전국 커피숍 규모 파악
df <- read.csv('r-ggagi-data/example_coffee.csv', header = T, stringsAsFactors = T)
size <- df$sizeOfsite
str(size)
summary(size)
# 아웃라이어(이상치) 삭제 (평균보다 지나치게 다른 값)
# 이상치를 NA로 바꾼 뒤 하단에서 모든 NA값 제거
size[size > 10000] <- NA
size[size == 0] <- NA
# NA값 삭제(결측치 : 없는 값)
size <- size[complete.cases(size)]
summary(size)
# 20단위 계급 생성
degree_size <- table(cut(size, breaks = (0:72)*20))
degree_size
# 시각화
ggplot(data=df, aes(x=sizeOfsite)) +
geom_freqpoly(binwidth=10, size=1.2, colour='orange') +
scale_x_continuous(limits = c(0,300), breaks = seq(0,300,20)) +
theme_wsj()
# 데이터 불러오기
# 인구수에 ","가 있어 문자열로 불러오기 stringAsFactors = F
df <- read.csv('r-ggagi-data/example_population.csv', stringsAsFactors = F)
str(df)
# 자료 값 확인
head(df)
# 문자열 분리 : stringr 패키지 설치
#install.packages('stringr')
# 라이브러리
library('stringr')
df[,1]
# ( 기준으로 지역과 인구 수를 분리
temp <- str_split_fixed(df[,1], '\\(', 2)
head(temp)
# 공백 기준으로 시 구 분리
new_city <- str_split_fixed(temp[,1], ' ',2)
head(new_city)
# 변수명 변경
colnames(new_city) <- c('Provinces', 'City')
head(new_city)
# 데이터프레임 생성
df_new <- data.frame(new_city, df[,c(2:7)])
df_new[df_new$Provinces =='세종특별자치시',]
# 시티 공백 제거
df_new[df_new == ' '] <- NA
head(df_new)
df_new[df_new$Provinces =='세종특별자치시',]
# NA가 존재하는 행 제거
df_new2 <- df_new[complete.cases(df_new),] # ,는 모든 칼럼을 가져옴을 의미
head(df_new2)
df_new2[df_new2$Provinces =='세종특별자치시',]
head(complete.cases(df_new))
# is.na() NA가 있는 값 TRUE
head(is.na(df_new))
# NA가 있는 행 불러오기
df_new3 <- df_new[is.na(df_new$City),]
head(df_new3)
# =
df_new4 <- df_new[!complete.cases(df_new),]
head(df_new4)
# 인구수 변수 "," 처리하고 수치형으로 반환
str(df_new2)
for(i in 3:8){
df_new2[,i] <- sapply(df_new2[,i], function(x) gsub(',','',x)) # ','를 ''으로 변환해서 다시 담기
df_new2[,i] <- as.numeric(df_new2[,i]) # 수치(문자->숫자)화해서 다시 담기
}
df_fin <- df_new2
head(df_fin)
# 그룹별로 동일한 함수 적용 - tapply(적용할 변수, 그룹지을 변수, 적용할 함수)
# ex. tapply(height, sex, mean) : 성별로 키 값 평균
sum_pop <- tapply(df_fin$Population, df_fin$Provinces,sum) # : 지역별로 인구 합계
sum_pop
# 레벨 값이 남아있어 세종특별자치시가 나타나는 경우 삭제
df_fin[,1] <- factor(df_fin[,1]) # 값이 없는 level 삭제
sum_pop <- tapply(df_fin$Population, df_fin$Provinces,sum)
sum_pop
# 시각화, aes : 축 생성을 의미
ggplot(df_fin, aes(x=Provinces, y=Population, fill=Provinces)) +
# = ggplot(data=df_fin, aes(x=df_fin$Provinces, y=Population, fill=Provinces)) +
geom_bar(stat='identity') +
theme_wsj()
write.csv(df_fin, 'example_pop_final.csv')