wasmetqall
wasmetqall

Reputation: 139

How to compare date between 2 tibbles?

mydf<-data.frame(x=as.Date("2017-1-1"))
mydf[1,1]-as.Date("2017-10-16")

Time difference of -288 days

mytb<-tibble(x=as.Date("2017-1-1"))
mytb[1,1]-as.Date("2017-10-16")

Error in mytb[1, 1] - as.Date("2017-10-16") : non-numeric argument to binary operator In addition: Warning message: Incompatible methods ("Ops.data.frame", "-.Date") for "-"

How to compare the date in tibble? I have a solution: convert tibble to dataframe, but is there any more feasible idea?

Upvotes: 1

Views: 602

Answers (1)

akrun
akrun

Reputation: 887511

There is potentially a difference in behavior between data.frame vs. tibble/data_frame. With data.frame, the drop = TRUE

mydf[1,1]
#[1] "2017-01-01"

changes the data.frame to a vector when there is subsetting of single row/column etc.

But, it is not the case with tibble

mytb[1,1]
# A tibble: 1 x 1
#  x         
#   <date>    
#1 2017-01-01

It is still a tibble. So we need to extract it with either $ or [[

mytb[['x']][1]
#[1] "2017-01-01"

The tidyverse option would be pull

mytb %>%
     pull(x) %>%
     magrittr::extract(1) %>%
     magrittr::subtract(as.Date("2017-10-16"))
#Time difference of -288 days

Upvotes: 4

Related Questions