Nice programing

R에서 플로팅 목적으로 POSIXct에서 시간 및 초 추출

nicepro 2020. 12. 12. 12:27
반응형

R에서 플로팅 목적으로 POSIXct에서 시간 및 초 추출


다음이 있다고 가정합니다. data.frame foo

           start.time duration
1 2012-02-06 15:47:00      1
2 2012-02-06 15:02:00      2
3 2012-02-22 10:08:00      3
4 2012-02-22 09:32:00      4
5 2012-03-21 13:47:00      5

그리고 class(foo$start.time)반환

[1] "POSIXct" "POSIXt" 

foo$durationv. 의 플롯을 만들고 싶습니다 foo$start.time. 내 시나리오에서는 실제 날짜가 아닌 시간에만 관심이 있습니다. POSIXct벡터 클래스 에서 시간을 시간 : 초로 추출하는 방법은 무엇입니까?


이것은 좋은 질문이며 R에서 날짜를 처리하는 데 어려움이 있음을 강조합니다. 윤활유 패키지는 매우 편리합니다. 따라서 아래에서는베이스 (@ RJ-에서 제안한대로)를 사용하는 방법과 윤활유를 사용하는 방법의 두 가지 방법을 제시합니다.

원본 게시물에서 데이터 프레임의 처음 두 행을 다시 만듭니다.

foo <- data.frame(start.time = c("2012-02-06 15:47:00", 
                                 "2012-02-06 15:02:00",
                                 "2012-02-22 10:08:00"),
                  duration   = c(1,2,3))

POSIXct 및 POSIXt 클래스로 변환 (이 작업을 수행하는 두 가지 방법)

# using base::strptime
t.str <- strptime(foo$start.time, "%Y-%m-%d %H:%M:%S")

# using lubridate::ymd_hms
library(lubridate)
t.lub <- ymd_hms(foo$start.time)

이제 시간을 십진수 시간으로 추출하십시오.

# using base::format
h.str <- as.numeric(format(t.str, "%H")) +
               as.numeric(format(t.str, "%M"))/60

# using lubridate::hour and lubridate::minute
h.lub <- hour(t.lub) + minute(t.lub)/60

이러한 접근 방식이 동일 함을 보여줍니다.

identical(h.str, h.lub)

그런 다음 위의 접근 방식 중 하나를 선택하여 십진수 시간을 할당합니다 foo$hr.

foo$hr <- h.str

# If you prefer, the choice can be made at random:
foo$hr <- if(runif(1) > 0.5){ h.str } else { h.lub }

그런 다음 ggplot2 패키지를 사용하여 플로팅합니다.

library(ggplot2)
qplot(foo$hr, foo$duration) + 
             scale_x_datetime(labels = "%S:00")

기본 R에 의존 할 수 있습니다.

# Using R 2.14.2
# The same toy data
foo <- data.frame(start.time = c("2012-02-06 15:47:00", 
                                 "2012-02-06 15:02:00",
                                 "2012-02-22 10:08:00"),
                  duration   = c(1,2,3))

클래스 POSIXct에는 구조화 된 방식으로 날짜-시간 정보가 포함되어 substr있으므로 POSIXct 벡터 내의 시간 위치에서 문자를 추출 할 수 있습니다 . 즉, POSIXct의 형식 (인쇄시 표시되는 방식)을 알고 있으면 시간과 분을 추출 할 수 있습니다.

# Extract hour and minute as a character vector, of the form "%H:%M"
substr(foo$start.time, 12, 16)

그런 다음 임의의 날짜에 붙여 넣어 다시 POSIXct로 변환합니다. 이 예에서는 2012 년 1 월 1 일을 사용하지만 날짜를 지정하지 않고 대신 formatR을 사용하면 현재 날짜를 사용합니다.

# Store time information as POSIXct, using an arbitrary date
foo$time <- as.POSIXct(paste("2012-01-01", substr(foo$start.time, 12, 16)))

그리고 모두 plotggplot2방법 POSIXct의 형식 배 상자 밖으로 알고있다.

# Plot it using base graphics
plot(duration~time, data=foo)

# Plot it using ggplot2 (0.9.2.1)
library(ggplot2)
qplot(x=time, y=duration, data=foo)

이 코드는 문자열로 변환하고 다시 숫자로 변환하는 것보다 훨씬 빠릅니다.

time <- c("1979-11-13T08:37:19-0500", "2014-05-13T08:37:19-0400");
time.posix <- as.POSIXct(time, format = "%Y-%m-%dT%H:%M:%S%z");
time.epoch <- as.vector(unclass(time.posix));
time.poslt <- as.POSIXlt(time.posix, tz = "America/New_York");
time.hour.new.york <- time.poslt$hour + time.poslt$min/60 + time.poslt$sec/3600;

> time;
[1] "1979-11-13T08:37:19-0500" "2014-05-13T08:37:19-0400"
> time.posix;
[1] "1979-11-13 15:37:19 IST" "2014-05-13 15:37:19 IDT"
> time.poslt;
[1] "1979-11-13 08:37:19 EST" "2014-05-13 08:37:19 EDT"
> time.epoch;
[1]  311348239 1399984639
> time.hour.new.york;
[1] 8.621944 8.621944

Lubridate doesn't handle time of day data, so Hadley recommends the hms package for this type of data. Something like this would work:

library(lubridate)
foo <- data.frame(start.time = parse_datetime(c("2012-02-06 15:47:00", 
                                 "2012-02-06 15:02:00",
                                 "2012-02-22 10:08:00")),
                  duration   = c(1,2,3))


foo<-foo %>% mutate(time_of_day=hms::hms(second(start.time),minute(start.time),hour(start.time)))

Watch out for 2 potential issues - 1) lubridate has a different function called hms and 2) hms::hms takes the arguments in the opposite order to that suggested by its name (so that just seconds may be supplied)


It is ancient topic, but I have found very few questions and answers about this matter. My solution is the following

library(hms)
foo <- data.frame(start.time = c("2012-02-06 15:47:00", 
                             "2012-02-06 15:02:00",
                             "2012-02-22 10:08:00"),
              duration   = c(1,2,3))

foo$start.time = as.POSIXct( foo$start.time )

g1 = ggplot( ) + xlab("") + 
  geom_line( data = foo, aes(x = as.hms(start.time), y = duration ), color = "steelblue" )
g1

If you would like to add manual time (!) breaks, then

time_breaks =    as.POSIXlt(c(
                   "2012-02-06 12:35:00 MSK", 
                   "2012-02-06 13:15:00 MSK",
                   "2012-02-06 14:22:00 MSK",
                   "2012-02-06 15:22:00 MSK"))
 g1 + 
  scale_x_time( breaks = as.hms( time_breaks ) ) +
  theme(  axis.text.x = element_text( angle=45, vjust=0.25) ) 

참고URL : https://stackoverflow.com/questions/10705328/extract-hours-and-seconds-from-posixct-for-plotting-purposes-in-r

반응형