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?
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).
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") .
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.
Method 1: Use as.numeric() as. This will return the number of seconds that have passed between your date object and 1/1/1970.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With