When importing from Googlesheets, returns a list I can't convert to date in R

Viewed 59

when I import from GoogleSheets one of the variables comes as a list. This is a sample:

> dataset$my_date[1:4]
[[1]]
[1] "2019-06-25 UTC"

[[2]]
[1] "2019-06-25 UTC"

[[3]]
[1] "2019-06-25 UTC"

[[4]]
[1] "2019-06-25 UTC"

But when I try to convert this list to date, it returns me:

> as.Date(dataset$my_date[1:4])
Error in as.Date.default(dataset$my_date[1:4]) : 
  do not know how to convert 'dataset$my_date[1:4]' to class “Date”

Is there a way to set this variable as vector when reading with read_sheet() function?

1 Answers

It is a list and according to ?as.Date

x - The as.Date methods accept character strings, factors, logical NA and objects of classes "POSIXlt" and "POSIXct"

methods(as.Date)
#[1] as.Date.character   as.Date.default     as.Date.factor      as.Date.IDate       as.Date.numeric     as.Date.POSIXct    
#[7] as.Date.POSIXlt     as.Date.vctrs_sclr* as.Date.vctrs_vctr*

As there is no list method for as.Date, we need to concatenate them with c to convert to a vector (invoked with do.call )

as.Date(do.call(c, dataset$my_date))

If there are NULL elements, convert it to NA

dataset$my_data[sapply(dataset$my_data, is.null)] <- NA
as.Date(do.call(c, dataset$my_date))

Or using unlist (if it is not a Datetime class i.e. a character vector)

as.Date(unlist(dataset$my_date))

It can be reproduced with

lst1 <- list(Sys.time(), Sys.time())
as.Date(lst1)

Error in as.Date.default(lst1) : do not know how to convert 'lst1' to class “Date”

By converting to vector

as.Date(do.call(c, lst1))
#[1] "2020-09-13" "2020-09-13"
Related