R

[R] 날짜/시간 데이터 다루기 ( as.POSIXct / as.Date)

AKIRA24 2024. 7. 15. 17:54
728x90

R Studio에서 날짜/시간 데이터를 다루게 될 때 사용했던 POSIXct와 Date에 대하여

    > str(df)
    'data.frame':	179839 obs. of  16 variables:
     $ market_id                                   : int  1 2 3 3 3 3 3 3 2 3 ...
     $ created_at                                  : chr  "2015-02-06 22:24" "2015-02-10 21:49" "2015-01-22 20:39" "2015-02-03 21:21" ...
     $ actual_delivery_time                        : chr  "2015-02-06 23:27" "2015-02-10 22:56" "2015-01-22 21:09" "2015-02-03 22:13" ...
     $ store_id                                    : int  1845 5477 5477 5477 5477 5477 5477 5477 5477 5477 ...
     $ store_primary_category                      : chr  "american" "mexican" NA NA ...
     $ order_protocol                              : int  1 2 1 1 1 1 1 1 3 1 ...
     $ total_items                                 : int  4 1 1 6 3 3 2 4 4 2 ...
     $ subtotal                                    : int  3441 1900 1900 6900 3900 5000 3900 4850 4771 2100 ...
     $ num_distinct_items                          : int  4 1 1 5 3 3 2 4 3 2 ...
     $ min_item_price                              : int  557 1400 1900 600 1100 1500 1200 750 820 700 ...
     $ max_item_price                              : int  1239 1400 1900 1800 1600 1900 2700 1800 1604 1200 ...
     $ total_onshift_dashers                       : int  33 1 1 1 6 2 10 7 8 2 ...
     $ total_busy_dashers                          : int  14 2 0 1 6 2 9 8 6 2 ...
     $ total_outstanding_orders                    : int  21 2 0 2 9 2 9 7 18 2 ...
     $ estimated_order_place_duration              : int  446 446 446 446 446 446 446 446 446 446 ...
     $ estimated_store_to_consumer_driving_duration: int  861 690 690 289 650 338 638 626 289 715 ..
    > head(df$created_at,10)
     [1] "2015-02-06 22:24" "2015-02-10 21:49" "2015-01-22 20:39" "2015-02-03 21:21" "2015-02-15 2:40" 
     [6] "2015-01-28 20:30" "2015-01-31 2:16"  "2015-02-12 3:03"  "2015-02-16 0:11"  "2015-02-18 1:15"

 

데이터를 살펴보면 create_at은 날짜 형태의 객체를 띄고 있지만 변수는 chr타입으로 되어있다.

이 상태로는 날짜 형태의 그래프를 그린다거나 할 수 없어 날짜 형태로 변환하여 사용 하기로 했다.

 

    > df$create <- as.Date(df$created_at,format = "%Y-%m-%d %H:%M")
    > str(df$create)
     Date[1:179839], format: "2015-02-06" "2015-02-10" "2015-01-22" "2015-02-03" "2015-02-15" "2015-01-28" "2015-01-31" ...

 

as.Date를 사용한 결과이다. format에서 지정했던 그대로 연,월,일 데이터가 나왔지만 시간, 분의 데이터는 사라졌다.

여기서 나는 시간과 분 데이터도 필요한 경우여서 as.POSIXct 를 사용하여 시,분을 유지했다.

    > df$create <- as.POSIXct(df$created_at, format="%Y-%m-%d %H:%M")
    > str(df$create)
     POSIXct[1:179839], format: "2015-02-06 22:24:00" "2015-02-10 21:49:00" "2015-01-22 20:39:00" "2015-02-03 21:21:00" ...

 

 

as.Date를 사용했을 때와는 다르게 시,분,초의 데이터를 전부 유지한 채로 chr 에서 날짜 형식으로 변환할 수 있었다.

다만 요일로의 변환, 년,월,일 데이터를 따로 나누어 쓰게 될 경우 as.Date를 사용하는 쪽이 더 편할 것 같다.

'R' 카테고리의 다른 글

[R] 기초 다지기 (기본 연산/combine/paste/collapse)  (0) 2024.07.10