Convert yyyymmdd string to Date class in R - r

I would like to convert these dates with format YYYYMMDD to a Date class.
dates <- data.frame(Date = c("20130707", "20130706", "20130705", "20130704"))
I tried:
dates <- as.Date(dates, "%Y%m%d")
And I get the following error:
Error in as.Date.default(dates, "%Y%m%d") :
do not know how to convert 'dates' to class "Date"
What would be the correct way to set this format?

You need to provide the Date column, not the entire data.frame.
R> as.Date(dates[["Date"]], "%Y%m%d")
[1] "2013-07-07" "2013-07-06" "2013-07-05" "2013-07-04"

An extra conversion to characters works for me:
dates<-as.Date(as.character(dates),format="%Y%m%d")
Without the conversion the following error occurs:
dates<-as.Date(dates,format="%Y%m%d")
Error in as.Date.numeric(dates, format = "%Y%m%d") :
'origin' must be supplied
Different error but this might help, works for POSIXct too, paste date and hours, format %Y%m%d%H

Classic R:
> start_numeric <- as.Date('20170215', format = '%Y%m%d');
> start_numeric
[1] "2017-02-15"
> format(start_numeric, "%Y%m%d")
[1] "20170215"

Use the lubridate package for an easy conversion:
date_test <- data.frame(Date = c("20130707", "20130706", "20130705", "20130704"))
date_test$Date <- ymd(date_test$Date)
date_test
Date
1 2013-07-07
2 2013-07-06
3 2013-07-05
4 2013-07-04

Instead of using brackets, you can use variable name:
dates <- data.frame(Date = c("20130707", "20130706", "20130705", "20130704"))
as.Date(dates$Date, "%Y%m%d")
[1] "2013-07-07" "2013-07-06" "2013-07-05" "2013-07-04"

Related

Getting Wrong date format as result in R

I am trying to separate a date from a column in a database, but the result date format is not proper.
column data = "24-01-2021 19:15"
Code used:
database_1$date <- format(as.Date(database_1$start_time), "%d-%m-%Y")
Result: 20-01-0024
Expected result: 24-01-2021
Update:
I just realized the expected output:
just add format("%d.%m.%Y") to the code:
as.Date(dmy_hm(column_date)) %>%
format("%d.%m.%Y")
[1] "24.01.2021"
With lubridate package you can:
With dmy_hm you read in the character column_date to date format
Then you can add as.Date
library(lubridate)
column_date <- "24-01-2021 19:15"
as.Date(dmy_hm(column_date))
[1] "2021-01-24"

R convert time (xx:xx:xx) to min. as.POSIXct returns error "character string is not in a standard unambiguous format"

I have some data about focus times in xx:xx:xx format that I would like to add together over several sessions. So I am trying to convert each of them to minutes or any format that can be summed and understood. I've tried as.POSIX.ct but I get the error in the title. I've also tried lubidate hms(day1)/60 and I get another error. Here's a shortened reproducible example.
day1 <- c("01:05:38", "00:56:54", "00:48:17")
day2 <- c("00:37:57", "00:21:09", "00:43:34")
day1convert <- as.numeric(as.POSIXct(day1), units = "mins")
This returns the error: "Error in as.POSIXlt.character(x, tz, ...) :
character string is not in a standard unambiguous format"
library(lubridate)
convert<-hms(day1)/60
This returns the error:"Error in validObject(.Object) :
invalid class “Period” object: periods must have integer values
Any help would be appreciated.
Not exactly sure what is your expected output but you can try the following to get time in minutes.
library(lubridate)
period_to_seconds(hms(day1))/60
#[1] 65.63333 56.90000 48.28333
If you want to convert time to POSIXct format
as.POSIXct(day1, format = "%T", tz = "UTC")
#[1] "2020-02-15 01:05:38 UTC" "2020-02-15 00:56:54 UTC" "2020-02-15 00:48:17 UTC"
In base R:
sapply(strsplit(day1, ":"), function(x) as.difftime(sum(c(60, 1, 1/60)*as.numeric(x)), units="mins"))
#> [1] 65.63333 56.90000 48.28333
1) chron::times Use chron times class. They can be added and if we convert them to numeric they are given in fractions of a day.
library(chron)
times(day1) + times(day2)
## [1] 01:43:35 01:18:03 01:31:51
as.numeric(times(day1) + times(day2))
## [1] 0.07193287 0.05420139 0.06378472
2) data.table::as.ITime Another possibility is data.table's ITime. They can be added or converting to numeric gives seconds.
library(data.table)
as.ITime(day1) + as.ITime(day2)
## [1] "01:43:35" "01:18:03" "01:31:51"
as.numeric(as.ITime(day1) + as.ITime(day2))
## [1] 6215 4683 5511

How to change date format from YYYY/MM/DD to DD/MM/YYYY

I have a column of dates which were read in as character values (yes, they are supposed to be the same):
str(df$date)
$ date : chr "30/08/2017" "30/08/2017" "30/08/2017" "30/08/2017"
I then convert the values to Date format:
str(df$date)
$ date : Date, format: "2017-08-30" "2017-08-30" "2017-08-30"
The problem is that no matter which method I choose to use, the resulting dates are always in YYYY/MM/DD format, which is not what I want; they should be in DD/MM/YYYY format.
I try:
df$date <- as.Date(df$date, format = "%d/%m/%Y")
df$date <- strptime(df$date, format = "%d/%m/%Y")
df$date <- as.POSIXct(df$date, format = "%d/%m/%Y")
and they all produce the same format.
I have read numerous similar Stack Overflow posts as well as some guides and have tried things like getting and setting my system locale (United Kingdom) and all is correct in that respect.
Where am I going wrong?
I try:
df$date <- as.Date(df$date, format = "%d/%m/%Y")
df$date <- strptime(df$date, format = "%d/%m/%Y")
df$date <- as.POSIXct(df$date, format = "%d/%m/%Y")
and they all produce the same format.
R has two very similarly named functions: strptime, which converts from character strings to Date data, and strftime, which converts Dates to formatted strings. To make matters worse, the documentation for these two functions is combined, so it can be very hard to keep their uses straight. You want strftime, in this case.
You can also use format:
date = c("30/08/2017", "30/08/2017", "30/08/2017", "30/08/2017")
date <- as.Date(date, format = "%d/%m/%Y")
# > date
# [1] "2017-08-30" "2017-08-30" "2017-08-30" "2017-08-30"
date = format(date, "%m/%d/%Y")
# > date
# [1] "08/30/2017" "08/30/2017" "08/30/2017" "08/30/2017"
Turns into character class:
# > class(date)
# [1] "character"
This will help you:
$variable = '2018/09/18';
$date = str_replace('/', '/', $variable);
echo date('d/m/Y', strtotime($date));
Please check and let me know if you need any more help.

Convert string to date with different types of time format

I have a dataframe as bellow
library(lubridate)
Date <- c("18.11.2016 21:03:41", "19.11.2016", "20.11.2016","21.11.2016")
df = data.frame(Date)
df
I to get
df$Date
[1] "2016-11-18" "2016-11-19" "2016-11-20" "2016-11-21"
& try to convert it to date like this
df$Date = dmy(df$Date)
and I get
Warning message:
1 failed to parse.
How to fix it?
Try this:
s <- c("2004-03-21 12:45:33.123456", # ISO
"2004/03/21 12:45:33.123456", # variant
"20040321", # just dates work fine as well
"Mar/21/2004", # US format, also support month abbreviation or full
"rapunzel") # will produce a NA
p <- toPOSIXct(s)
options("digits.secs"=6) # make sure we see microseconds in output
print(format(p, tz="UTC")
Read about it more here.

Convert integer to class Date

I have an integer which I want to convert to class Date. I assume I first need to convert it to a string, but how?
My attempt:
v <- 20081101
date <- as.Date(v, format("%Y%m%d"))
Error in charToDate(x) : character string is not in a standard
unambiguous format
Using paste() works, but is that really the correct way to do the conversion?
date <- as.Date(paste(v), format("%Y%m%d"))
date
[1] "2008-11-01"
class(date)
# [1] "Date"
as.character() would be the general way rather than use paste() for its side effect
> v <- 20081101
> date <- as.Date(as.character(v), format = "%Y%m%d")
> date
[1] "2008-11-01"
(I presume this is a simple example and something like this:
v <- "20081101"
isn't possible?)
Another way to get the same result:
date <- strptime(v,format="%Y%m%d")
You can use ymd from lubridate
lubridate::ymd(v)
#[1] "2008-11-01"
Or anytime::anydate
anytime::anydate(v)
#[1] "2008-11-01"

Resources