如何解释从ggvis handle_click返回的日期

时间:2015-05-24 04:05:59

标签: r date ggvis

使用handle_click

的第一次体验
library(ggvis)
library(dplyr)

# create data.frame
counts <- c(1,2)
dates <- as.Date(c("2015-01-01","2015-01-02"))
df <- data.frame(count=counts,date=dates)


# function to view clicked data
getDate = function(data,location,session){
  if(is.null(data)) return(NULL)
  glimpse(data)
}

df %>% 
  ggvis(~date,~count) %>% 
  layer_points() %>% 
  handle_click(getDate)

单击第一个点时返回

Observations: 1
Variables:
$ date  (dbl) 1.42007e+12
$ count (int) 1

TIA

1 个答案:

答案 0 :(得分:0)

日期显示为原始时间的毫秒数,被视为1970-01-01 00:00:00

如您所见,您可以使用以下方法将其转换回原始日期:

> as.POSIXct(1.42007e+12/1000, origin='1970-01-01 00:00:00 GMT')
[1] "2014-12-31 23:53:20 GMT"

6分钟的错误是由于我认为的舍入错误。

您可以更改脚本以查看日期,因为它们应如下所示:

# function to view clicked data
getDate = function(data,location,session){
  if(is.null(data)) return(NULL)
  #just added the below line in your code
  data$date <- as.Date(as.POSIXct((data$date)/1000, origin='1970-01-01 00:10:00 GMT'))
  glimpse(data)
}

df %>% 
  ggvis(~date,~count) %>% 
  layer_points() %>% 
  handle_click(getDate)

点击后返回:

Observations: 1
Variables:
$ date  (date) 2015-01-01
$ count (dbl) 1