0

I am trying to convert times series data from Apple Health export into an xts format. However, I can not manage to get the right data format.

new = health_df %>% 
  mutate(
    Type = str_remove(type, "HKQuantityTypeIdentifier"), 
    Value = as.numeric(as.character(value)),
    Date = as_datetime(creationDate)) %>%
  filter(Type == 'HeartRate') %>% 
  select(Date, Type, Value)
> head(new)
# A tibble: 6 x 3
  Date                Type      Value
  <dttm>              <chr>     <dbl>
1 2021-07-27 13:12:32 HeartRate    80
2 2021-07-27 13:12:38 HeartRate    79
3 2021-07-27 13:12:42 HeartRate    76
4 2021-07-27 13:12:47 HeartRate    73
5 2021-07-27 13:12:52 HeartRate    71
6 2021-07-27 13:12:57 HeartRate    71
> class(new$Date)
[1] "POSIXct" "POSIXt" 
> new = as.xts(new, dateFormat = "POSIXct")
Error in as.POSIXlt.character(x, tz, ...) : 
  character string is not in a standard unambiguous format

Error in as.POSIXlt.character(x, tz, ...) : character string is not in a standard unambiguous format

I checked the class an everything seems fine though... I also tried to specify the format

Date = as.POSIXct((Date), format = "%Y.%m.%d %H:%M:%S", tz="GMT"))

but this didn't work either.

Maybe I am on the wrong track, I appreciate your help! Best C

C_Hut
  • 31
  • 8
  • Looking at your dates, the format should be "%Y-%m-%d %H:%M:%S", tz="GMT". Also the way you are using as.xts will result in a character matrix. You need to remove Date and Type from the data.frame if you want an xts matrix. – phiver Oct 26 '21 at 10:56

1 Answers1

1

As @phiver mentioned you need to keep only numeric data in the xts matrix. Also since the Date column is already of type POSIXct you don't need to change that. Try -

new_xts <- xts::xts(new$Value, order.by = new$Date)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thank you! new_xts <- xts::xts(new$Value, order.by = new$Date) worked! head(new_xts) [,1] 2021-07-27 13:12:32 80 2021-07-27 13:12:38 79 2021-07-27 13:12:42 76 seems fine! But interesengtingly, in Rstudio view the dates look like: X2021.07.27.13.12.32 80.0000 X2021.07.27.13.12.38 79.0000 X2021.07.27.13.12.42 – C_Hut Oct 26 '21 at 11:11