# 패키지 설치
install.packages('hflights')
# 공통 패키지 로드
library(ggplot2)
library(hflights)
# 구조 살펴보기 - str()
str(hflights)
# 일부 확인 - head()
head(hflights)
# 특정 변수 확인
dest_table <- table(hflights$Dest)
dest_table
# 명목형 변수 개수 확인 - length() 벡터나 리스트등 개수 확인 함수
length(dest_table)
# 범위 살펴보기 - range() 가장 큰값, 작은값
range(dest_table)
# 가장 큰값, 작은값의 이름 찾기
dest_table[dest_table == 1] # 오거스타 리저널 공항
dest_table[dest_table == 9820] # 댈러스 공항
# 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)
head(df, 3)
# 연령대별 도수 - 연속형 변수, 구간 나누기 (0~10], (10~20] ...
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
# 시각화 1
barplot(age_table)
# 시각화 2
install.packages('ggthemes')
library('ggplot2')
library('ggthemes')
# aes 축
ggplot(data=df, aes(x=age)) +
geom_freqpoly(binwidth=10, size=1.4, colour='orange') +
theme_wsj()
# 데이터 로드
# read.csv의 옵션 default 값은 T
df <- read.csv('r-ggagi-data/example_coffee.csv', header = T, stringsAsFactors = T)
# 데이터 구조 파악
str(df)
# 불필요한 변수 제거
# 로우데이터를 같은 변수로 하면 수정 할 때 문제생김 (df2를 df2로 할 경우)
df2 <- subset(df, select=c(-adressBystreet, -dateOfclosure, -startdateOfcessation, -duedateOfcessation, -dateOfreOpen, -zip))
str(df2)
# 최초 커피숍 찾기
range(df2$yearOfStart)
# 결측치를 제거해야 출력됨
range(df2$yearOfStart, na.rm=T) # 결측치 제거
subset(df2, subset = (yearOfStart == 1964))
# 가장 오래된 운영중인 커피숍 찾기
df_filter <- subset(df2, subset = (stateOfbusiness == '운영중'))
range(df_filter$yearOfStart, na.rm = T) # 결측치 제거
subset(df_filter, subset = (yearOfStart == 1967))
head(subset(df_filter, subset = (yearOfStart == 2015)))
tail(subset(df_filter, subset = (yearOfStart == 2015)))
# 해마다 오픈하는 커피숍 개수 찾기
table(df2$yearOfStart)
# 시각화 1
qplot(data=df2, yearOfStart, geom='bar')
# 2000년부터 성장, 2010년부터 급성장
# 1999년 스타벅스 1호점 입점
# 분할표 작성 - 운영중 / 폐업
stat_table <- table(df2$stateOfbusiness, df2$yearOfStart)
stat_table
# 조건으로 특정 컬럼값 찾기 - which(), rownames 열조건 colnames
# 조건이 TRUE일 때만 찾아줌
# colnames(stat_table) == 1993
which(colnames(stat_table) == 1993)
which.max(colnames(stat_table))
# 원하는 컬럼으로 분할
stat_table_26_93 <- stat_table[,c(26:48)]
stat_table_26_93
# 비율 계산
stat_prop_table <- prop.table(stat_table_26_93, margin = 2) # margin = 2 열 기준
stat_prop_table
# 데이터 프레임 구성
input1 <- stat_table_26_93
input2 <- stat_prop_table
# df_bind <- data.frame(colnames(input1))
# df_bind <- data.frame(colnames(input1),input1[1,])
# df_bind <- data.frame(colnames(input1),input1[1,],input1[2,])
# df_bind <- data.frame(colnames(input1),input1[1,],input1[2,],input2[1,])
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
# 시각화 - linie graph
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) +
geom_point(aes(y=Open), colour='red', size=3) +
theme_bw()
head(df)
# 규모 데이터 별도 저장
size <- df$sizeOfsite
# 자료 특성 파악 str, summary 많이사용
# summary() 기본 통계값 보여줌
summary(size)
# 아웃라이어(이상치) 삭제 - 평균보다 지나치게 다른 값
size[size > 10000] <- NA
size[size == 0] <- NA
# 결측치 제거(NA 값 제거) - complete.cases() NA 값 false리턴
size <- size[complete.cases(size)]
summary(size)
# 20단위 계급 생성
degree_size <- table(cut(size, breaks=(0:72)*20))
degree_size
# 시각화 - 30~40 (10평) 제일 많음
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()
# Data 불러오기
df <- read.csv('r-ggagi-data/example_population.csv', stringsAsFactors = F)
# 자료 살펴보기
str(df)
# 자료 값 확인 head()
head(df)
# 서울특별시 종로구 (1111000000) => 서울특별시 종로구 이렇게 만들기
# 문자열 분리 - str_split_fixed()
install.packages('stringr')
library('stringr')
# ( 기준으로 2개 분리
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)
# 새로운 dataframe 생성
df_new <- data.frame(new_city, df[,c(2:7)])
df_new[df_new$Provinces == '세종특별자치시',]
# City 공백 => NA
df_new[df_new == ' '] <- NA
head(df_new)
df_new[df_new$Provinces == '세종특별자치시',]
# NA 행 삭제 - complete.cases() NA 가 있는 행 FALSE
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),]
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(적용할 변수, 그룹지을 변수, 적용할 변수)
# tapply(heigh, sex, mean) - 성별로 키 값 평균
# 도(첫번째 변수)별 인구수 합계
sum_pop <- tapply(df_fin$Population, df_fin$Provinces, sum)
sum_pop
# Level 값이 남아있어 나온 세종특별자치시 삭제
df_fin[, 1] <- factor(df_fin[, 1]) #값이 없는 level 삭제됨
sum_pop <- tapply(df_fin$Population, df_fin$Provinces, sum)
sum_pop
# 시각화 - ggplot()
library('ggplot2')
library('ggthemes')
ggplot(df_fin, aes(x=Provinces, y=Population, fill=Provinces)) +
geom_bar(stat='identity') + theme_wsj()
# csv로 저장하기
write.csv(df_fin, 'example_population_f.csv')