Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting date in Year.decimal form in R

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?

like image 376
monkeyshines Avatar asked Nov 17 '14 04:11

monkeyshines


People also ask

How do you convert a date into a decimal?

yyyy represents the year, mm represents the month (01-12), dd represents the day (01-31) and ddd represents the day of the year (001-366).

How do I convert to year in R?

To get the year from a date in R you can use the functions as. POSIXct() and format() . For example, here's how to extract the year from a date: 1) date <- as. POSIXct("02/03/2014 10:41:00", format = "%m/%d/%Y %H:%M:%S) , and 2) format(date, format="%Y") .

How do I change date format in R?

To format = , provide a character string (in quotes) that represents the current date format using the special “strptime” abbreviations below. For example, if your character dates are currently in the format “DD/MM/YYYY”, like “24/04/1968”, then you would use format = "%d/%m/%Y" to convert the values into dates.

How do I change date format to numeric in R?

Method 1: Use as.numeric() as. This will return the number of seconds that have passed between your date object and 1/1/1970.


1 Answers

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.

like image 190
Rich Scriven Avatar answered Sep 17 '22 22:09

Rich Scriven