Tidy Data
같은 자료를 4 가지의 다른 방법으로 표현
dataset 을 tidy 하게 만들기 위한 3 가지의 기본 규칙
- 각 변수는 각자의 column 을 가지고 있어야 한다
- 각 observation 은 각자의 row 를 가지고 있어야 한다
- 각 값은 각자의 cell 을 가지고 있어야 한다
tidy 자료의 장점
- 자료를 저장하는데에 일관된 방법을 제공하고 이후 작업을 위한 도구들을 이에 맞춰
개발하므로 배우기 쉽다 - 변수를 column 으로 놓는 것은 특히 유용. R 의 내장된 함수들은 vector 를 기본으로 하고
있으므로 tidy data 를 vector 로 변환하는 것이 유용
library(tidyverse)
- 인구 10,000명 당의 cases로 바꾸기
table1 %>%
mutate(rate = cases / population * 10000)
country year cases population rate
<chr> <dbl> <dbl> <dbl> <dbl>
1 Afghanistan 1999 745 19987071 0.373
2 Afghanistan 2000 2666 20595360 1.29
3 Brazil 1999 37737 172006362 2.19
4 Brazil 2000 80488 174504898 4.61
5 China 1999 212258 1272915272 1.67
6 China 2000 213766 1280428583 1.67
- 각 year별로 case를 weight로 해서 합침 → 각 year별 case 확인
table1 %>%
count(year, wt = cases)
year n
<dbl> <dbl>
1 1999 250740
2 2000 296920
- 각 year별 case 시각화 → 각 나라별 line 확인(group=country)
library(ggplot2)
ggplot(table1, aes(year, cases)) +
geom_line(aes(group = country), colour = "grey50") +
geom_point(aes(colour = country))
pivot_wider and pivot_longer
- 대부분의 자료는 분석보다는 모아지기 편리한 형태로 구성되므로 tidy data 로 바꾸는 작업이
필요 - 하나의 변수를 multiple column 에, 혹은 하나의 관측을 여러 줄에 표현해야될 수 있다 - pivot_longer() 과 pivot_wider()의 함수를 이용
pivot_longer
table4a
country `1999` `2000`
<chr> <dbl> <dbl>
1 Afghanistan 745 2666
2 Brazil 37737 80488
3 China 212258 213766
- `1999` 와 `2000`는 변수의 이름이 아니고 year 변수의 값이 됨
- row 는 하나가 아니고 2 개의 관측을 나타낸다
- tidy 자료로 만들기 위해서 column 을 새로운 변수의 pair 로 만들어야함. 이를 pivot_longer 이라고 함. 이를 위하여 3 가지의 인자를 지정
1) 값을 나타내는 column 의 이름; table4a 에서는 1999 와 2000
2) column 의 이름에 나타난 값을 위한 변수 이름 (names_to); ‘year’
3) column 에서 가지고 있는 값을 저장하기 위한 변수 이름 (values_to);‘cases’
table4a %>%
pivot_longer(c(`1999`,`2000`), names_to = "year", values_to = "cases")
country year cases
<chr> <chr> <dbl>
1 Afghanistan 1999 745
2 Afghanistan 2000 2666
3 Brazil 1999 37737
4 Brazil 2000 80488
5 China 1999 212258
6 China 2000 213766
- 1999, 2000등 숫자 변수를 chr로 인식하는 것을 알 수 있음 → 추후 변환 필요
- table4b 도 같은 형태로 변형 가능
table4b %>%
pivot_longer(c(`1999`,`2000`), names_to = "year", values_to = "population")
Afghanistan 1999 19987071
2 Afghanistan 2000 20595360
3 Brazil 1999 172006362
4 Brazil 2000 174504898
5 China 1999 1272915272
6 China 2000 1280428583
- table4a 와 table4b 를 tidy data 로 바꾼 후 dplyr 패키지의 left_join()를 이용하여 하나의
tibble 로 나타내기
tidy4a <- table4a %>%
pivot_longer(c(`1999`,`2000`), names_to = "year", values_to = "cases")
tidy4b <- table4b %>%
pivot_longer(c(`1999`,`2000`), names_to = "year", values_to = "population")
left_join(tidy4a, tidy4b)
pivot_wider
- pivot_wider 은 pivot_longer 의 반대로 observation 이 여러줄에 나타날 때 이용
- 위의 자료를 tidy 자료로 바꾸기 위해서는 두가지의 인자가 필요
1) 변수 이름이 저장되어 있는 column (names_from): 여기서는 type
2) 변수의 값이 저장되어 있는 column (values_from): 여기서는 count
pivot_wider(table2, names_from = type, values_from = count)
country year cases population
<chr> <dbl> <dbl> <dbl>
1 Afghanistan 1999 745 19987071
2 Afghanistan 2000 2666 20595360
3 Brazil 1999 37737 172006362
4 Brazil 2000 80488 174504898
5 China 1999 212258 1272915272
6 China 2000 213766 1280428583
Separating and uniting
- table3 의 “하나의 column 에 두변수의 값”을 가지고 있는 문제를 separate()과 unite()을
이용하여 해결 - separate(): 하나의 column 을 여러 column 으로 바꿔주는 것으로 어떤 문자로 나누어져있던
간에 나 여러 column 으로 분할해 줌
- rate 를 cases 와 population 으로 분리
table3 %>%
separate(rate, into = c("cases", "population"))
country year cases population
<chr> <dbl> <chr> <chr>
1 Afghanistan 1999 745 19987071
2 Afghanistan 2000 2666 20595360
3 Brazil 1999 37737 172006362
4 Brazil 2000 80488 174504898
5 China 1999 212258 1272915272
6 China 2000 213766 1280428583
- sep 을 이용하여 특정 문자로 분할
table3 %>%
separate(rate, into = c("cases", "population"), sep = "/")
country year cases population
<chr> <dbl> <chr> <chr>
1 Afghanistan 1999 745 19987071
2 Afghanistan 2000 2666 20595360
3 Brazil 1999 37737 172006362
4 Brazil 2000 80488 174504898
5 China 1999 212258 1272915272
6 China 2000 213766 1280428583
- convert 옵션을 이용하여 알맞는 type 으로 변경
table3 %>%
separate(rate, into = c("cases", "population"), convert = TRUE)
country year cases population
<chr> <dbl> <int> <int>
1 Afghanistan 1999 745 19987071
2 Afghanistan 2000 2666 20595360
3 Brazil 1999 37737 172006362
4 Brazil 2000 80488 174504898
5 China 1999 212258 1272915272
6 China 2000 213766 1280428583
- sep=k 로 나누는 문자 개수 지정
table3 %>%
separate(year, into = c("century", "year"), sep = 2)
country century year rate
<chr> <chr> <chr> <chr>
1 Afghanistan 19 99 745/19987071
2 Afghanistan 20 00 2666/20595360
3 Brazil 19 99 37737/172006362
4 Brazil 20 00 80488/174504898
5 China 19 99 212258/1272915272
6 China 20 00 213766/1280428583
unite(): 여러개의 column 을 하나의 column 으로 합쳐줌
table5 %>%
unite(new, century, year)
country new rate
<chr> <chr> <chr>
1 Afghanistan 19_99 745/19987071
2 Afghanistan 20_00 2666/20595360
3 Brazil 19_99 37737/172006362
4 Brazil 20_00 80488/174504898
5 China 19_99 212258/1272915272
6 China 20_00 213766/1280428583
- sep 옵션을 이용하여 연결문자 지정
table5 %>%
unite(new, century, year, sep = "")
country new rate
<chr> <chr> <chr>
1 Afghanistan 1999 745/19987071
2 Afghanistan 2000 2666/20595360
3 Brazil 1999 37737/172006362
4 Brazil 2000 80488/174504898
5 China 1999 212258/1272915272
6 China 2000 213766/1280428583
Relational data
관계형 data 에 대하여 작업을 하기위해 알아야 하는 용어
- mutation joins: 하나의 data frame 에 다른 data frame 을 matching 시켜 새로운 변수
만들기 - filtering joins : 하나의 data frame 에서 다른 data frame 의 자료와 맞는 관측이 있는지를
확인하여 자료를 걸러내기 - set operations: 관측을 마치 set element 인것처럼 다루기
nycflights13
library(nycflights13)
flights
- airlines : 비행사 code 자료. carrier 의 full name 정보
airlines
- airports: 공항 자료, 공항 code 인 faa 와 각 공항의 정보들
airports
- planes: 각 비행기 정보. tailnum 으로 비행기 구분
planes
- weather`: NYC 공항의 시간별 날씨 정보
weather
Planes
- tailnum(항공기 등록번호)을 기준으로 빈도를 계산 후, 빈도가 1보다 큰 경우 필터링 진행
planes %>%
count(tailnum) %>%
filter(n > 1)
→ 중복된 항공기만 추출 가능
- weather 데이터셋에서 연도, 월, 일, 시간, 출발지를 기준으로 빈도 계산 후, 빈도가 1보다 큰 경우 필터링 작업
weather %>%
count(year, month, day, hour, origin) %>%
filter(n > 1)
→ 중복된 날짜, 시간, 출발지의 날씨 데이터 추출 가능
- flights 데이터셋에서 연도, 월, 일, 항공편을 기준으로 빈도를 계산하고, 그 중에서 빈도가 1보다 큰 경우만 선택
flights %>%
count(year, month, day, flight) %>%
filter(n > 1)
year month day flight n
<int> <int> <int> <int> <int>
1 2013 1 1 1 2
2 2013 1 1 3 2
3 2013 1 1 4 2
4 2013 1 1 11 3
5 2013 1 1 15 2
6 2013 1 1 21 2
7 2013 1 1 27 4
8 2013 1 1 31 2
9 2013 1 1 32 2
10 2013 1 1 35 2
# ℹ 29,758 more rows
→ 중복된 날짜와 항공편 정보를 추출
Mutating joins
- 두 table 을 이용하여 변수를 합성하는 방법
- 먼저 key 를 이용하여 observation 을 맞추고 한 table 에서 다른 table 로 변수를 copy
- mutate 함수와 같이 join 함수는 변수를 오른쪽에 추가. 새로운 변수는 인쇄되지 않음
- 필요한 데이터프레임 생성
flights2 <- flights %>%
select(year:day, hour, origin, dest, tailnum, carrier)
flights2
- origin과 dest 열을 제외한 나머지 열들을 선택한 뒤, airlines 데이터프레임과 carrier 열을 기준으로 왼쪽 조인(left join)을 수행
flights2 %>%
select(-origin, -dest) %>%
left_join(airlines, by = "carrier")
→ flights2 데이터프레임에서 origin과 dest 열을 제외한 열들을 선택하고, 이를 airlines 데이터프레임과 carrier 열을 기준으로 왼쪽 조인한다. 왼쪽 조인을 통해 flights2 데이터프레임의 각 행에 해당하는 carrier 값이 airlines 데이터프레임에서 일치하는 행의 열들이 추가된다. 이를 통해 airlines 데이터프레임의 추가 정보를 포함한 새로운 데이터프레임을 얻을 수 있다.
Inner Join (교집합)
- join 의 가장 단순한 형태. key 가 같은 pair 찾기
- inner join 에서는 키가 맞지 않는 자료는 모두 제외됨
x <- data.frame(key=1:3,
val_x = c("x1","x2","x3"))
y <- data.frame(key=c(1,2,4),
val_y = c("y1","y2","y3"))
x %>%
inner_join(y, by = "key")
## key val_x val_y
## 1 1 x1 y1
## 2 2 x2 y2
Outer Join
- 모든 observation 을 유지. 1. left join: 첫번째 table 의 모든 observation 유지 2. right join: 두번째 table 에 있는 모든 observation 유지 3. full join: 두 table 의 모든 observation 유지
x %>%
left_join(y, by = "key")
## key val_x val_y
## 1 1 x1 y1
## 2 2 x2 y2
## 3 3 x3 <NA>
x %>%
right_join(y, by = "key")
## key val_x val_y
## 1 1 x1 y1
## 2 2 x2 y2
## 3 4 <NA> y3
x %>%
full_join(y, by = "key")
## key val_x val_y
## 1 1 x1 y1
## 2 2 x2 y2
## 3 3 x3 <NA>
## 4 4 <NA> y3
뒷 내용 공부 필요....ㅎㄷㄷ 어렵당
'Data visualization > 데이터시각화(R)' 카테고리의 다른 글
데이터시각화(R)_Texas flight data (0) | 2023.11.11 |
---|---|
데이터시각화(R)_탐색적 자료분석 EDA (0) | 2023.11.01 |
데이터시각화(R)_nycflights13 Flights (1) | 2023.10.21 |
데이터시각화(R)_Data Import (0) | 2023.10.17 |
데이터시각화(R)_Tibbles2 (0) | 2023.10.15 |