Data visualization/데이터시각화(R)

데이터시각화(R)_Tibbles

뉴욕킴 2023. 10. 15. 13:31
  • iris 데이터 불러오기 
library(tidyverse)
head(iris)
class(iris)
  • iris를 tibble로 저장하기
irisT=as_tibble(iris)
irisT
 Sepal.Length Sepal.Width Petal.Length Petal.Width
          <dbl>       <dbl>        <dbl>       <dbl>
 1          5.1         3.5          1.4         0.2
 2          4.9         3            1.4         0.2
 3          4.7         3.2          1.3         0.2
 4          4.6         3.1          1.5         0.2
 5          5           3.6          1.4         0.2
 6          5.4         3.9          1.7         0.4
 7          4.6         3.4          1.4         0.3
 8          5           3.4          1.5         0.2
 9          4.4         2.9          1.4         0.2
10          4.9         3.1          1.5         0.1
class(irisT)
"tbl_df"     "tbl"        "data.frame"
  • tibble()을 이용하여 데이터셋 만들기 
tibble(x=1:5, y=1, z=x^2+y)
 A tibble: 5 × 3
      x     y     z
  <int> <dbl> <dbl>
1     1     1     2
2     2     1     5
3     3     1    10
4     4     1    17
5     5     1    26

  • newtibble 생성
newtibble<-tibble(
 a = lubridate::now() + runif(1e3) * 86400,
 a1 = lubridate::now() + runif(1e3) * 86400*30, 
 b = lubridate::today() + runif(1e3) * 30,
 b2 = lubridate::today() + runif(1e3) * 30 *12, 
 c = 1:1e3,
 d = runif(1e3),
 e = sample(letters, 1e3, replace = TRUE),
 f = sample(LETTERS, 1e3, replace = TRUE)
)
newtibble
A tibble: 1,000 × 8
   a                   a1                  b         
   <dttm>              <dttm>              <date>    
 1 2023-10-15 13:01:42 2023-10-19 14:31:51 2023-10-20
 2 2023-10-15 20:54:33 2023-10-27 10:48:54 2023-11-07
 3 2023-10-16 08:48:56 2023-10-20 10:08:16 2023-10-15
 4 2023-10-15 21:10:51 2023-10-22 14:22:40 2023-11-07
 5 2023-10-16 03:48:01 2023-10-17 18:23:23 2023-11-09
 6 2023-10-16 01:39:14 2023-10-22 02:05:45 2023-11-08
 7 2023-10-15 20:10:09 2023-10-20 01:33:40 2023-10-25
 8 2023-10-15 20:48:40 2023-10-20 21:18:38 2023-10-15
 9 2023-10-16 05:16:19 2023-11-05 13:49:49 2023-10-23
10 2023-10-15 13:16:17 2023-10-27 21:43:12 2023-11-01
# ℹ 990 more rows
# ℹ 5 more variables: b2 <date>, c <int>, d <dbl>,
#   e <chr>, f <chr>
# ℹ Use `print(n = ...)` to see more rows
  • 3개만 보이게 설정 : n=3
print(newtibble,n=3)
<dttm>              <dttm>              <date>    
1 2023-10-15 13:01:42 2023-10-19 14:31:51 2023-10-20
2 2023-10-15 20:54:33 2023-10-27 10:48:54 2023-11-07
3 2023-10-16 08:48:56 2023-10-20 10:08:16 2023-10-15
  • 모든 변수를 다 보이게 설정 : width=Inf
print(newtibble,n=3,width=Inf)
A tibble: 1,000 × 8
  a                   a1                  b         
  <dttm>              <dttm>              <date>    
1 2023-10-15 13:01:42 2023-10-19 14:31:51 2023-10-20
2 2023-10-15 20:54:33 2023-10-27 10:48:54 2023-11-07
3 2023-10-16 08:48:56 2023-10-20 10:08:16 2023-10-15
  b2             c     d e     f    
  <date>     <int> <dbl> <chr> <chr>
1 2024-03-05     1 0.172 r     I    
2 2024-08-07     2 0.436 i     Z    
3 2023-12-24     3 0.816 k     I    
# ℹ 997 more rows
# ℹ Use `print(n = ...)` to see more rows
  • 모든 자료를 추출 : print_min=Inf
print(newtibble,n=3,print_min=Inf)
A tibble: 1,000 × 8
  a                   a1                  b         
  <dttm>              <dttm>              <date>    
1 2023-10-15 13:01:42 2023-10-19 14:31:51 2023-10-20
2 2023-10-15 20:54:33 2023-10-27 10:48:54 2023-11-07
3 2023-10-16 08:48:56 2023-10-20 10:08:16 2023-10-15
# ℹ 997 more rows
# ℹ 5 more variables: b2 <date>, c <int>, d <dbl>,
#   e <chr>, f <chr>
# ℹ Use `print(n = ...)` to see more rows
  • view()
 view(newtibble)


  • 현재 시간 추출 : lubridate
lubridate::now()
"2023-10-15 12:02:19 KST"
  • 오늘 날짜 추출 
lubridate::today()
 "2023-10-15"

  • df 변수 생성
df <- tibble(
 x = runif(5),
 y = rnorm(5)
)
  • df의 x 추출
df$x
[1] 0.8690751 0.5463841 0.2615122 0.9350569 0.9499957
  • 2번째 변수 추출: df[[2]]
df[[2]]
[1] -1.2692912  1.4342061  0.4806600 -0.5617053 -0.9616756

dplyr을 이용한 자료 변환
  • flights data (‘nycflights13’ library)
  • 2013 년 New York 으로부터 출발하는 모든 비행기에 대한 자료
  • 변수들

  • 라이브러리 설치 및 불러오기  
install.packages("nycflights13")
library(nycflights13)
library(tidyverse)
flights
 year month   day dep_time sched_dep_time dep_delay
   <int> <int> <int>    <int>          <int>     <dbl>
 1  2013     1     1      517            515         2
 2  2013     1     1      533            529         4

- 515 : 5시 15분

- 529 : 5시 29분

 

dplyr 의 기본 함수

• filter(): 조건에 맞는 관측 선택하기

• arrange(): 자료에서 관측의 순서 바꾸기

• select(): 변수 선택

• mutate(): 새로운 변수 만들기

• summarise(): 자료 요약하기

 

 

  • 1월 1일 ~ 1월 2일 자료 추출
filter(flights, month == 1, day <= 2)
A tibble: 1,785 × 19
    year month   day dep_time sched_dep_time dep_delay
   <int> <int> <int>    <int>          <int>     <dbl>
 1  2013     1     1      517            515         2
 2  2013     1     1      533            529         4
 3  2013     1     1      542            540         2
 4  2013     1     1      544            545        -1
 5  2013     1     1      554            600        -6
 6  2013     1     1      554            558        -4
 7  2013     1     1      555            600        -5
 8  2013     1     1      557            600        -3
 9  2013     1     1      557            600        -3
10  2013     1     1      558            600        -2
# ℹ 1,775 more rows
# ℹ 13 more variables: arr_time <int>,
#   sched_arr_time <int>, arr_delay <dbl>, carrier <chr>,
#   flight <int>, tailnum <chr>, origin <chr>, dest <chr>,
#   air_time <dbl>, distance <dbl>, hour <dbl>,
#   minute <dbl>, time_hour <dttm>
# ℹ Use `print(n = ...)` to see more rows
view(filter(flights, month == 1, day <= 2))

 

  • 11월~12월 자료 추출 : 11월 or 12월 / %로 뽑는 방법 2가지 있음
filter(flights, month == 11 | month == 12)
filter(flights,month %in% c(11,12))

수치연산의 비교
sqrt(2) ^ 2 == 2
## [1] FALSE

- sqrt(2)^2 와 2가 같은지 비교 → 부동 소수점 연산의 한계로 정확한 값이 아니라 FALSE 반환 

1/49 * 49 == 1
## [1] FALSE

- 1/49*49와 1이 같은지 비교 → 부동 소수점 연산의 한계로 정확한 값이 아니라 FALSE 반환

 

  •  near() 함수로 근사적 비교 → 두 값의 사이의 차이가 적을 경우 동등하다고 판단 
near(sqrt(2) ^ 2, 2)
## [1] TRUE
near(1 / 49 * 49, 1)
## [1] TRUE

Arrange rows with arrange()

• 지정한 변수의 크기 순으로 자료를 정렬하기

arrange(flights, year, month, day)
A tibble: 336,776 × 19
    year month   day dep_time sched_dep_time dep_delay
   <int> <int> <int>    <int>          <int>     <dbl>
 1  2013     1     1      517            515         2
 2  2013     1     1      533            529         4
 3  2013     1     1      542            540         2
 4  2013     1     1      544            545        -1
 5  2013     1     1      554            600        -6
 6  2013     1     1      554            558        -4
 7  2013     1     1      555            600        -5
 8  2013     1     1      557            600        -3
 9  2013     1     1      557            600        -3
10  2013     1     1      558            600        -2
# ℹ 336,766 more rows
# ℹ 13 more variables: arr_time <int>,
#   sched_arr_time <int>, arr_delay <dbl>, carrier <chr>,
#   flight <int>, tailnum <chr>, origin <chr>, dest <chr>,
#   air_time <dbl>, distance <dbl>, hour <dbl>,
#   minute <dbl>, time_hour <dttm>
# ℹ Use `print(n = ...)` to see more rows
  • desc(dep_time) : 출발 시간 늦은 것부터 정렬 / 내림차순 
arrange(flights, year, month, day, desc(dep_time))
year month   day dep_time sched_dep_time dep_delay
   <int> <int> <int>    <int>          <int>     <dbl>
 1  2013     1     1     2356           2359        -3
 2  2013     1     1     2353           2359        -6
 3  2013     1     1     2353           2359        -6
 4  2013     1     1     2343           1724       379
 5  2013     1     1     2327           2250        37
  • NA 값은 항상 마지막순서
df <- tibble(x = c(5, 2, NA))
arrange(df, x)
arrange(df, desc(x))
# A tibble: 3 × 1
      x
  <dbl>
1     5
2     2
3    NA

 

Select columns with select() 
  • 나열한 변수만을 선택 : (year:day)
select(flights, year:day)

- year:day → year부터 day까지 끌어옴 

 

  • 제거할 변수 선택 : -(year:day)
select(flights, -(year:day))

 

  • starts_with("abc"): “abc”로 시작하는 이름의 변수 선택 
  • ends_with("xyz"): “xyz”로 끝나는 이름의 변수 선택
  • contains("ijk"): “ijk”가 들어있는 이름의 변수 선택
  • num_range("x", 1:3): x1, x2, x3 선택
  • rename(): 변수 이름 바꾸기
rename(flights, tail_num = tailnum)
  • everything(): 나머지 모든 변수를 의미
select(flights, time_hour, air_time, everything())
 A tibble: 336,776 × 19
   time_hour           air_time  year month   day dep_time
   <dttm>                 <dbl> <int> <int> <int>    <int>
 1 2013-01-01 05:00:00      227  2013     1     1      517
 2 2013-01-01 05:00:00      227  2013     1     1      533
 3 2013-01-01 05:00:00      160  2013     1     1      542
 4 2013-01-01 05:00:00      183  2013     1     1      544
 5 2013-01-01 06:00:00      116  2013     1     1      554
 6 2013-01-01 05:00:00      150  2013     1     1      554
 7 2013-01-01 06:00:00      158  2013     1     1      555
 8 2013-01-01 06:00:00       53  2013     1     1      557
 9 2013-01-01 06:00:00      140  2013     1     1      557
10 2013-01-01 06:00:00      138  2013     1     1      558

- time_hour와 air_time 변수를 선택하고 everything() 함수를 이용하여 나머지 모든 변수를 포함시킴

- 원하는 변수만 선택하여 새로운 데이터셋 만들 수 있음

 

Add new variables with mutate()
  • 새로운 변수를 만들어 기존 자료에 추가
flights_sml <- select(flights, 
 year:day, 
 ends_with("delay"), 
 distance, 
 air_time
)
mutate(flights_sml,
 gain = arr_delay - dep_delay,
 hours = air_time / 60,
 gain_per_hour = gain / hours
)

 

  • transmute(): 새로 만든 변수만을 가지는 자료 만들기
transmute(flights,
 gain = arr_delay - dep_delay,
 hours = air_time / 60,
 gain_per_hour = gain / hours
)

 

20%/%3
## [1] 6
20%%3
## [1] 2

 

  • flights 의 dep_time 변수를 이용하여 출발 시간, 출발 분에 대한 변수를 만들기
transmute(flights,
 dep_time,
 hour = dep_time %/% 100,
 minute = dep_time %% 100
)

 

Grouped summaries with summarise() 
  • 요약 통계량 계산 
summarise(flights, delay = mean(dep_delay, na.rm = TRUE))

 

  • group_by()와 함께 사용할 경우 유용
by_day <- group_by(flights, year, month, day)
by_day

summarise(by_day, delay = mean(dep_delay, na.rm = TRUE))