Home > Blockchain >  Lubridate dmy_hms mutate error, incorrect size
Lubridate dmy_hms mutate error, incorrect size

Time:10-17

I would like to convert this table's datetime object to one with a dmy hms date variable in order to conduct anomaly detection modelling:

datetime transactionvalue
2021-01-01 04:00:00 2435.88
2021-01-01 04:00:00 885.27

So I use this code:

transactions_ts%>%
  mutate(Transaction_datetime = dmy_hms(Transaction_datetime, format = "%y-%m-%d %H:%M:%S"))

And it gives me the error

Error in mutate(., Transaction_datetime = dmy_hms(Transaction_datetime, : 

✖ `Transaction_datetime` must be size 2 or 1, not 3.

What can I do to fix this? Why won't it parse the date data?

CodePudding user response:

I suspect the problem is that you're using dmy_hms() (i.e. day-month-year hour-minute-second) instead of ymd_hms() (year-month-day hour-mninute-second). Also, you don't need to specify a format if the date is 'standard' i.e. "y-m-d h:m:s".

Here is an example illustrating the correct usage:

library(tidyverse)
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union

df <- read.table(text = "rownumber datetime transactionvalue
1 '2021-01-01 04:00:00' 2435.88
2 '2021-01-01 04:00:00' 885.27", header = TRUE)

df
#>   rownumber            datetime transactionvalue
#> 1         1 2021-01-01 04:00:00          2435.88
#> 2         2 2021-01-01 04:00:00           885.27

df %>%
  mutate(Transaction_datetime = ymd_hms(datetime)) %>%
  str()
#> 'data.frame':    2 obs. of  4 variables:
#>  $ rownumber           : int  1 2
#>  $ datetime            : chr  "2021-01-01 04:00:00" "2021-01-01 04:00:00"
#>  $ transactionvalue    : num  2436 885
#>  $ Transaction_datetime: POSIXct, format: "2021-01-01 04:00:00" "2021-01-01 04:00:00"

Created on 2022-10-17 by the reprex package (v2.0.1)

  • Related