Programing

연도와 월 ( "yyyy-mm"형식)을 날짜로 변환 하시겠습니까?

lottogame 2020. 10. 5. 07:27
반응형

연도와 월 ( "yyyy-mm"형식)을 날짜로 변환 하시겠습니까?


다음과 같은 데이터 세트가 있습니다.

Month    count
2009-01  12
2009-02  310
2009-03  2379
2009-04  234
2009-05  14
2009-08  1
2009-09  34
2009-10  2386

데이터를 플로팅하고 싶습니다 (월은 x 값으로 계산하고 y 값으로 계산). 데이터에 차이가 있기 때문에 이달의 정보를 날짜로 변환하고 싶습니다. 나는 시도했다 :

as.Date("2009-03", "%Y-%m")

그러나 그것은 작동하지 않았습니다. 뭐가 문제 야? as.Date ()도 하루가 필요하고 하루의 표준 값을 설정할 수없는 것 같습니다. 내 문제를 해결하는 기능은 무엇입니까?


이 시도. (여기 text=Lines에서는 예제를 자체 포함 된 상태로 유지하는 데 사용 하지만 실제로는 파일 이름으로 대체합니다.)

Lines <- "2009-01  12
2009-02  310
2009-03  2379
2009-04  234
2009-05  14
2009-08  1
2009-09  34
2009-10  2386"

library(zoo)
z <- read.zoo(text = Lines, FUN = as.yearmon)
plot(z)

X 축은이 데이터로 그리 예쁘지 않지만 실제로 더 많은 데이터가있는 경우 괜찮을 수 있거나의 예제 섹션에 표시된 멋진 X 축에 대한 코드를 사용할 수 있습니다 ?plot.zoo.

z위에서 만든 동물원 시리즈 에는 "yearmon"시간 인덱스가 있으며 다음과 같습니다.

> z
Jan 2009 Feb 2009 Mar 2009 Apr 2009 May 2009 Aug 2009 Sep 2009 Oct 2009 
      12      310     2379      234       14        1       34     2386 

"yearmon" 단독으로도 사용할 수 있습니다.

> as.yearmon("2000-03")
[1] "Mar 2000"

노트 :

  1. "yearmon" 클래스 객체는 달력 순서로 정렬됩니다.

  2. 이것은 원할 가능성이 높은 동일한 간격으로 월별 포인트를 표시합니다. 그러나 매월 일 수에 비례하여 간격이 다른 간격으로 점을 플로팅하려는 경우 인덱스 z"Date"class : 로 변환합니다 time(z) <- as.Date(time(z)).


날짜는 숫자 값과 시작 날짜에 해당하므로 실제로 날짜가 필요합니다. 데이터가 날짜 형식이어야하는 경우 날짜에 붙여 넣어 수동으로 매월 1 일로 날짜를 수정할 수 있습니다.

month <- "2009-03"
as.Date(paste(month,"-01",sep=""))

날짜가 날짜 형식이어야하는 경우 가장 간결한 솔루션 :

library(zoo)
month <- "2000-03"
as.Date(as.yearmon(month))
[1] "2000-03-01"

as.Date 매월 첫날을 yearmon 개체로 고정합니다.


-package parse_date_time또는 fast_strptime함수를 사용하여이를 수행 할 수도 있습니다 lubridate.

> parse_date_time(dates1, "ym")
[1] "2009-01-01 UTC" "2009-02-01 UTC" "2009-03-01 UTC"

> fast_strptime(dates1, "%Y-%m")
[1] "2009-01-01 UTC" "2009-02-01 UTC" "2009-03-01 UTC"

그 둘 사이의 차이 즉 parse_date_time하면서 lubridate 스타일 형식 사양 허용 fast_strptime동일한 포맷 사양이 필요 strptime.

시간대를 지정하려면- tz매개 변수를 사용할 수 있습니다 .

> parse_date_time(dates1, "ym", tz = "CET")
[1] "2009-01-01 CET" "2009-02-01 CET" "2009-03-01 CET"

날짜-시간 데이터에 truncated불규칙성이 있는 경우- 매개 변수를 사용하여 허용되는 불규칙성 수를 지정할 수 있습니다.

> parse_date_time(dates2, "ymdHMS", truncated = 3)
[1] "2012-06-01 12:23:00 UTC" "2012-06-01 12:00:00 UTC" "2012-06-01 00:00:00 UTC"

사용 된 데이터 :

dates1 <- c("2009-01","2009-02","2009-03")
dates2 <- c("2012-06-01 12:23","2012-06-01 12",'2012-06-01")

언제든지 패키지 사용 :

library(anytime)

anydate("2009-01")
# [1] "2009-01-01"

실제로 위에서 언급했듯이 (및 SO의 다른 곳에서) 문자열을 날짜로 변환하려면 특정 날짜가 필요합니다. 로부터 as.Date()매뉴얼 페이지 :

If the date string does not specify the date completely, the returned answer may be system-specific. The most common behaviour is to assume that a missing year, month or day is the current one. If it specifies a date incorrectly, reliable implementations will give an error and the date is reported as NA. Unfortunately some common implementations (such as glibc) are unreliable and guess at the intended meaning.

A simple solution would be to paste the date "01" to each date and use strptime() to indicate it as the first day of that month.


For those seeking a little more background on processing dates and times in R:

In R, times use POSIXct and POSIXlt classes and dates use the Date class.

Dates are stored as the number of days since January 1st, 1970 and times are stored as the number of seconds since January 1st, 1970.

So, for example:

d <- as.Date("1971-01-01")
unclass(d)  # one year after 1970-01-01
# [1] 365

pct <- Sys.time()  # in POSIXct
unclass(pct)  # number of seconds since 1970-01-01
# [1] 1450276559
plt <- as.POSIXlt(pct)
up <- unclass(plt)  # up is now a list containing the components of time
names(up)
# [1] "sec"    "min"    "hour"   "mday"   "mon"    "year"   "wday"   "yday"   "isdst"  "zone"  
# [11] "gmtoff"
up$hour
# [1] 9

To perform operations on dates and times:

plt - as.POSIXlt(d)
# Time difference of 16420.61 days

And to process dates, you can use strptime() (borrowing these examples from the manual page):

strptime("20/2/06 11:16:16.683", "%d/%m/%y %H:%M:%OS")
# [1] "2006-02-20 11:16:16 EST"

# And in vectorized form:
dates <- c("1jan1960", "2jan1960", "31mar1960", "30jul1960")
strptime(dates, "%d%b%Y")
# [1] "1960-01-01 EST" "1960-01-02 EST" "1960-03-31 EST" "1960-07-30 EDT"

I think @ben-rollert's solution is a good solution.

You just have to be careful if you want to use this solution in a function inside a new package.

When developping packages, it's recommended to use the syntaxe packagename::function_name() (see http://kbroman.org/pkg_primer/pages/depends.html).

In this case, you have to use the version of as.Date() defined by the zoo library.

Here is an example :

> devtools::session_info()
Session info ----------------------------------------------------------------------------------------------------------------------------------------------------
 setting  value                       
 version  R version 3.3.1 (2016-06-21)
 system   x86_64, linux-gnu           
 ui       RStudio (1.0.35)            
 language (EN)                        
 collate  C                           
 tz       <NA>                        
 date     2016-11-09                  

Packages --------------------------------------------------------------------------------------------------------------------------------------------------------

 package  * version date       source        
 devtools   1.12.0  2016-06-24 CRAN (R 3.3.1)
 digest     0.6.10  2016-08-02 CRAN (R 3.2.3)
 memoise    1.0.0   2016-01-29 CRAN (R 3.2.3)
 withr      1.0.2   2016-06-20 CRAN (R 3.2.3)

> as.Date(zoo::as.yearmon("1989-10", "%Y-%m")) 
Error in as.Date.default(zoo::as.yearmon("1989-10", "%Y-%m")) : 
  do not know how to convert 'zoo::as.yearmon("1989-10", "%Y-%m")' to class “Date”

> zoo::as.Date(zoo::as.yearmon("1989-10", "%Y-%m"))
[1] "1989-10-01"

So if you're developping a package, the good practice is to use :

zoo::as.Date(zoo::as.yearmon("1989-10", "%Y-%m"))

참고URL : https://stackoverflow.com/questions/6242955/converting-year-and-month-yyyy-mm-format-to-a-date

반응형