0

I read in an array from Excel using read_excel, and get two datetime columns, but what I need is two columns of dates

    User  DOB                 Answer_dt             Question Answer
   <chr>  <dttm>              <dttm>                   <int>  <int>
 1 User1  1900-01-01 00:00:00 2017-01-26 00:00:00        1      7
 2 User2  1900-01-01 00:00:00 2017-01-26 00:00:00        2      8

I would like the datetime columns to be converted to dates (the times are irrelevant), and have tried using mutate and lubridate in various combinations, but have succeeded only in getting an error message that I don't understand:

> library(lubridate)
> dt <- eML_daily[1, "DOB"]
> dt
# A tibble: 1 x 1
  DOB                
  <dttm>             
1 1900-01-01 00:00:00
Warning message:
`...` is not empty.

These dots only exist to allow future extensions and should be empty.
Did you misspecify an argument? 

> as_date(dt)
Error in as.Date.default(x, ...) : 
  do not know how to convert 'x' to class “Date”

> as_date(df[,"DOB"])
Error in as.Date.default(x, ...) : 
  do not know how to convert 'x' to class “Date”

I don't understand the warning messages, and can't quite see what I am doing wrong. Surely it should be a simple matter to convert from dttm to date and discard the time, which I don't need.

I'd be very appreciative for a pointer.

Sincerely and with many thanks in advance

Thomas Philips

Thomas Philips
  • 935
  • 2
  • 11
  • 22
  • Can you provide the data in `dput()` format? Please visit [this](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – UseR10085 Aug 03 '20 at 07:25

3 Answers3

1

In as_date(dt) you are attempting to convert a tibble to a datetime. That unsurprisingly fails. In as_date(df[,"DOB"]), I can't say what you are trying to do as you haven't given us df.

Working example;

library(tidyverse)
library(lubridate)

dt <- tibble(x=as_datetime("2017-01-26 00:00:00"))
dt
# A tibble: 1 x 1
  x                  
  <dttm>             
1 2017-01-26 00:00:00
dt %>% mutate(x=as_date(x))
# A tibble: 1 x 1
  x         
  <date>    
1 2017-01-26
Limey
  • 10,234
  • 2
  • 12
  • 32
1

You can use as.Date to convert date-time columns to date.

If you want to change columns 2 and 3 to date, you can do.

eML_daily[2:3] <- lapply(eML_daily[2:3], as.Date)

Or with dplyr :

library(dplyr)
eML_daily %>% mutate(across(2:3, as.Date))
#For dplyr < 1.0.0
#eML_daily %>% mutate_at(2:3, as.Date)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

Have you tried to convert it to character first?

Here's a quick sample:

x <- tibble(dt = c(Sys.time(),Sys.time() - 345767)) %>%
  mutate(dt = as_date(as.character(dt)))
Randall Helms
  • 849
  • 5
  • 15