I have a dataframe with a date column like the following:
19870703
19920929
20051015
20030613
How can I change the numeric Data to a Date format like %Y%m%d?
Neither as.date() nor as.POSIX.ct() works?
Using lubridate
date <- ymd("19870703")
in place of date you can put your column name
as.Date("19870703", "%Y%m%d")
[1] "1987-07-03"
Apply for entire column.
library(date)
as.date(your.date.vector)
Related
I have a full column of dates that are formatted like dd/mm/yyyy
I want the change the full column so that they are formatted like yyyy-mm-dd
Use dmy from lubridate
library(lubridate)
dmy("15/10/21")
[1] "2021-10-15"
I have my date column formats in 01-Oct-21 and I want to change them to 01-10-2021. Does anyone knows how to do this in R?
Thanks!
Using base R. You might need to convert your original column into Date format using
old_date <- as.Date('01-Oct-21', format = '%d-%b-%y')
Then you use the format function to get into what you what
format(old_date, '%d-%m-%Y')
It will look slightly different if your dates are in a data frame.
We can use
library(lubridate)
format(dmy("01-Oct-21"), '%d-%m-%Y')
[1] "01-10-2021"
I have a df with a column of the formate df$date = (1800.01, 1800.02, 1800.03) and so on.
And I can't figure out how to convert these numbers into proper monthly dates.
I tried the function date_decimal from the lubridate package, but that does not work for how my dates are formated.
Any ideas?
Probably the best way is to convert to a character first, then use one of the standard conversion functions. e.g.:
lubridate::ym(as.character(df$date))
I want to split date from DATE_H_REAL and have only date in my column
DATE_H_REAL DATE_H_REAL
02/02/2016 16:17 02/02/2016
I tried this but didn't work:
dataset1$DATE_H_REAL <- strptime(dataset1$DATE_H_REAL, format="%d/%m/%Y")
dataset1$DATE_H_REAL <- as.POSIXct(dataset1$DATE_H_REAL)
If you want to convert to a Date class, you can use as.Date() and precise the format of your input:
dataset1$DATE_H_REAL=as.Date(dataset1$DATE_H_REAL,format="%d/%m/%Y")
This returns a date:
[1] "2016-02-02"
In case your input column doesn't have a constant format, you can first extract the date before converting it to a Date class:
dataset1$DATE_H_REAL=gsub(".*(\\d{2}/\\d{2}/\\d{4}).*","\\1",dataset1$DATE_H_REAL)
dataset1$DATE_H_REAL=as.Date(dataset1$DATE_H_REAL,format="%d/%m/%Y");
I have a file with dates in the format YYYY-mm. I am trying to prepare my data for a time series analysis and therefore need to convert the formats from factor to a Date format.
What I've tried:
x <- '2011-11'
as.Date(as.character(a), "%Y-%m")
the last line gives me an output NA.
Thank you!
"2011-11" is not a date (where's the day)? Either add a day:
a <- '2011-11'
as.Date(paste0(a,'-01'))
or use zoo's yearmon class:
library(zoo)
as.yearmon(a)
'2011-11' isn't a date. Use paste(your.year.month.strs, '01', sep='-') to add the day component to your strings, then call as.Date with "%Y-%m-%d".