데이터 개념 이해하기¶
예제로 이해하기¶
hflights 패키지 - 20만건 이상의 데이터 예제 패키지¶
In [1]:
# 패키지 설치
install.packages('hflights')
In [2]:
# 공통 패키지 로드 (그림 그려주는 곳)
library(ggplot2)
In [3]:
library(hflights)
str() : 구조 살펴보기¶
In [4]:
str(hflights)
head 앞 부분 일부 확인¶
In [5]:
head(hflights)
table() : 특정 변수 확인¶
In [6]:
dest_table <- table(hflights$Dest)
dest_table
length() : 벡터나 리스트 등 갯수 확인 함수¶
In [7]:
# 명목형 변수 갯수 확인
length(dest_table)
range() : 가장 큰 값, 작은 값¶
In [8]:
# 범위 살펴보기
range(dest_table)
In [9]:
# 가장 큰 값, 작은 값의 이름 찾기
dest_table[dest_table == 1] # 오거스타 리저널 공항
dest_table[dest_table == 9820] # 댈러스 공항
In [10]:
# 5000 넘는 공항
dest_table_5000 <- dest_table[dest_table > 5000]
dest_table_5000
barplot() : 막대그래프 그리기¶
In [11]:
barplot(dest_table_5000)
대장암 환자 자료 분석¶
- 보건의료 빅데이터 개방 시스템
- http://opendata.hira.or.kr
- 어느 연령대에서 대장암이 많이 발생하는 지 조사
In [12]:
# 데이터 로드
df <- read.csv('R-ggagi-data/example_cancer.csv')
In [13]:
# 구조파악
str(df)
In [14]:
head(df, 3)
In [15]:
# 연령대별 도수 - 연속형 변수, 구간(계급) 나누기 (10대/20대...)
# cut()
age_table <- table(cut(df$age, breaks=(0:11)*10))
age_table
In [16]:
# 변수 이름 변경 - rownames()
rownames(age_table) <- c('1s','10s','20s','30s','40s','50s','60s','70s','80s','90s','100s')
age_table
In [17]:
# 시각화 1
barplot(age_table)
In [18]:
# 시각화 2
library(ggplot2)
library(ggthemes)
In [19]:
ggplot(data=df, aes(x=age))+
geom_freqpoly(binwidth=10, size=1.4, colour='orange')+
theme_wsj()
전국 커피숍 폐업/영업 상황 살펴보기¶
- 공공 데이터 포털
- https://www.data.go.kr
In [20]:
# 데이터 로드
df <- read.csv('R-ggagi-data/example_coffee.csv', head=T, stringsAsFactors = T)
In [21]:
# 데이터 구조 파악
str(df)
In [22]:
# 불필요한 변수 제거 -subset() 조건 걸 수 있음
df <- subset(df, select = c (-adressBystreet, -dateOfclosure,
-startdateOfcessation, -duedateOfcessation,
-dateOfreOpen, -zip))
str(df)
In [23]:
# 최초 커피숍 찾기
range(df$yearOfStart)
range(df$yearOfStart, na.rm=T) # 결측치 제거
subset(df, subset=(yearOfStart==1964))
In [24]:
# 현재 운영중인 가장 오래된 커피숍 찾기 - subset()
df_filter <- subset(df,subset=(stateOfbusiness == '운영중'))
range(df_filter$yearOfstart, na.rm=T) # 결측치 제거
subset(df_filter, subset=(yearOfStart==1967))
In [25]:
# 해마다 오픈하는 커피숍 갯수 찾기
table(df$yearOfStart)
In [26]:
# 데이터 시각화
# 2000년부터 성장, 2010년부터는 급성장
qplot(data=df, yearOfStart, geon='bar')
In [27]:
# 분할표 작성 (변수 2개) -운영중 /폐업
stat_table <- table(df$stateOfbusiness, df$yearOfStart)
stat_table
In [28]:
# 조건으로 특정 칼럼값 찾기 - which(), 행조건 rownames 열조건 colnames
which(colnames(stat_table)==1993) # 조건에 맞는 컬럼의 위치
which.max(colnames(stat_table)) # 가장 큰 값
In [29]:
stat_table_col_26_93 <- stat_table[,c(26:48)] # 행은 다 가져와, 열은 26~48까지
stat_table_col_26_93
In [30]:
# 비율 계산
# margin=2 열 기준
stat_prop_table <- prop.table(stat_table_col_26_93, margin=2)
stat_prop_table
In [31]:
# 데이터 프레임 구성
input1 <- stat_table_col_26_93
input2 <- stat_prop_table
In [32]:
# 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
In [33]:
# 행 열 이름 정리
# 행 이름 삭제
rownames(df_bind) <- NULL
colnames(df_bind) <- c('Year','Open','Close','POpen','PClose')
df_bind
In [34]:
# 시각화 - line graph
# 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) +
geom_point(aes(y=Open), colour='red', size=3) +
theme_bw()
전국 커피숍 규모 파악하기¶
In [35]:
# 데이터 로드
df <- read.csv('R-ggagi-data/example_coffee.csv', header=T, stringsAsFactors = T)
In [36]:
# 규모 데이터 별도 저장
size <- df$sizeOfsite
In [37]:
# 자료 특성 파악
summary(size)
In [38]:
# 아웃라이어(이상치)삭제 - 평균과 크게 다른 값
size[size > 10000] <- NA
size[size == 0] <- NA
In [39]:
# NA(결측치) 값 제거 - complete.cases() NA값 False 리턴
size <- size[complete.cases(size)]
In [40]:
summary(size)
In [41]:
# 20단위 계급 생성
degree_size <- table(cut(size, breaks=(0:72)*20))
degree_size
In [42]:
# 시각화 - 30~40(10평) 제일 많음
library(ggplot2)
library(ggthemes)
In [43]:
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()
전국 인구조사 자료 정리하기¶
- 통계청 작성 전국 인구조사 데이터
- 시별 도별 인구수
In [44]:
# data 불러오기
# 인구수에 "," 가 있어 문자열로 불러오기 stringdAsFactors = F ( factor 형이 아니라 문자열로!)
df <- read.csv('R-ggagi-data/example_population.csv', stringsAsFactors = F)
In [45]:
# 자료 요약 살펴보기
str(df)
In [46]:
# 자료 값 확인 - head()
head(df)
In [47]:
# 데이터 정제
# 서울특별시 종로구 (1111000000) -> 서울특별시 종로구 형태로 만들기
# 문자열 분리 - str_split_fixed()
install.packages('stringr')
In [48]:
library('stringr')
In [49]:
df[,1]
In [50]:
# ( 기준으로 2개 분리
temp <- str_split_fixed(df[,1], '\\(', 2)
head(temp)
In [51]:
# 공백 기준으로 시, 구 분리 -> 분리해야 더 다양한 분석 가능
new_city <- str_split_fixed(temp[,1], ' ', 2)
head(new_city)
In [52]:
# 변수명 변경
colnames(new_city) <- c('Provinces', 'City')
head(new_city)
In [53]:
# 새로운 dataframe 생성
df_new <- data.frame(new_city, df[,c(2:7)]) # 아까 분리했던거 포함해서 생성
df_new[df_new$Provinces == '세종특별자치시',]
In [54]:
# City 공백 -> NA
df_new[df_new == " "] <- NA
head(df_new)
df_new[df_new$Provinces == '세종특별자치시',]
In [55]:
# NA 행 삭제 - complete.cases() NA 가 있는 행 = FALSE
df_new2 <- df_new[complete.cases(df_new),]
head(df_new2)
df_new2[df_new2$Provinces == '세종특별자치시',]
In [56]:
head(complete.cases(df_new))
In [57]:
# is.na() - NA 가 있는 값 TRUE 반환
head(is.na(df_new))
In [58]:
# NA가 있는 행 불러오기
df_new3 <- df_new[is.na(df_new$City),]
df_new3
In [59]:
df_new4 <- df_new[!complete.cases(df_new),]
head(df_new4)
In [60]:
# 인구수 변수 "," 처리하고 수치형으로 변환
str(df_new2)
sapply() : 데이터 프레임 여러 변수에 함수 명령어 동시 적용¶
- 결과는 벡터 또는 행렬
- 참고 ) lapply() : 데이터 프레임 여러 변수에 함수 명령어 동시 적용 (결과는 리스트)
In [61]:
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
In [62]:
df_fin
tapply(적용할 변수, 그룹지을 변수, 적용할 함수) : 그룹별로 동일한 함수 적용¶
In [63]:
# tapply(height, sex, mean) : 성별별로 키값, 평균
# 도 (첫번 째 변수)별 인구수 합계
sum_pop <- tapply(df_fin$Population, df_fin$Provinces, sum)
sum_pop
In [64]:
# level 값이 남아있어 나온 세종특별자치시 삭제
df_fin[,1] <- factor(df_fin[,1]) # 값이 없는 level 삭제 됨
sum_pop <- tapply(df_fin$Population, df_fin$Provinces, sum)
sum_pop
시각화 - ggplot()¶
In [65]:
library('ggplot2')
library('ggthemes')
In [66]:
ggplot(df_fin, aes(x=Provinces, y=Population, fill=Provinces)) +
geom_bar(stat='identity') +
theme_wsj()
csv로 저장하기¶
In [67]:
write.csv(df_fin, 'example_population_f.csv')
In [ ]:
'R' 카테고리의 다른 글
[R] 기술통계 - 실전예제 (0) | 2020.07.08 |
---|---|
[R] 기술통계 (0) | 2020.07.08 |
[R] 데이터 개념 이해하기(2) (0) | 2020.07.03 |
[R] 필수 패키지 설치 및 외부 문서 읽어오기 (0) | 2020.07.02 |
[R] 데이터 개념 이해하기(기초) (0) | 2020.07.02 |
댓글