Converting date in Year.decimal form in R

不想你离开。 提交于 2019-11-26 08:34:54

问题


I have a ts column that saves years in decimal format ie

1988.0
1988.25
1988.5
1988.75

and so on. I need to export it to a .csv file with the date in a \"DD-MM-YYYY\" format.

How do I do this?


回答1:


The lubridate package has a function, date_decimal that you can use for this.

x <- c(1988.0, 1988.25, 1988.5, 1988.75)
library(lubridate)
(f <- format(date_decimal(x), "%d-%m-%Y"))
# [1] "01-01-1988" "01-04-1988" "02-07-1988" "01-10-1988"

Then you can write it to a csv with

write.csv(f, "afilename.csv")   ## or write.table()

You'll probably want to check the output first and adjust some of the arguments to whatever format you want.




回答2:


To deal with those year-fractions,

> date_string <- '1988.99'
> date_num <- as.numeric(date_string)
> year <- floor(date_num)
> year_beginning <- as.POSIXct(paste0(year, '-01-01'))
> year_end <- as.POSIXct(paste0(year+1, '-01-01'))
> date <- year_beginning + (date_num %% 1) * (year_end - year_beginning)
> format(date, format='%Y-%m-%d')
[1] "1988-12-28"

For writing a csv, try help(write.table)



来源:https://stackoverflow.com/questions/26965699/converting-date-in-year-decimal-form-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!