代码之家  ›  专栏  ›  技术社区  ›  Kim

对r日期和posixct的美学计算不同

  •  1
  • Kim  · 技术社区  · 6 年前

    我在工作时注意到一些很奇怪的事情 Date POSIXct 物体。请参见以下代码:

    library(tidyverse)
    library(Rmisc)
    
    test <- structure(list(
      date = structure(c(
        16863, 16866, 16862, 16743,
        16741, 16819, 16820, 16969, 16896, 16636, 16855, 16715, 16842,
        16899, 16859, 16860, 16827, 16823, 16912, 16878, 16848, 16839,
        16901, 16833, 16896, 16841, 16735, 16800, 16781, 16903
      ), class = "Date"),
      group = structure(c(
        1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 2L,
        2L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 1L,
        2L, 1L, 2L, 2L, 2L
      ), .Label = c("0", "1"), class = "factor")
    ), row.names = c(
      NA,
      -30L
    ), class = c("tbl_df", "tbl", "data.frame"))
    
    test$posix <- as.POSIXct(test$date)
    
    p1 <- ggplot(
      test, 
      aes(x = date, group = group, colour = group, fill = group)
    ) + 
      stat_density(aes(y = ..count..), alpha = 0.4)
    
    p2 <- ggplot(
      test, 
      aes(x = posix, group = group, colour = group, fill = group)
    ) + 
      stat_density(aes(y = ..count..), alpha = 0.4)
    
    multiplot(p1, p2)
    

    这将生成以下绘图:请参见Y轴。(计数<1,因为样本量太小。)

    enter image description here

    为什么这两张图上的比例不同 geom_density 具有 ..count.. 被叫来了?相同的时间 ..density.. 被称为。这两个情节的唯一区别是 x 美学或 日期 或与 posixct公司 . 我很困惑。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Kim    6 年前

    啊,这是个相当愚蠢的问题。我真傻。

    > as.numeric(test$posix)
     [1] 1456963200 1457222400 1456876800 1446595200 1446422400
     [6] 1453161600 1453248000 1466121600 1459814400 1437350400
    [11] 1456272000 1444176000 1455148800 1460073600 1456617600
    [16] 1456704000 1453852800 1453507200 1461196800 1458259200
    [21] 1455667200 1454889600 1460246400 1454371200 1459814400
    [26] 1455062400 1445904000 1451520000 1449878400 1460419200
    

    虽然

    > as.numeric(test$date)
     [1] 16863 16866 16862 16743 16741 16819 16820 16969 16896 16636
    [11] 16855 16715 16842 16899 16859 16860 16827 16823 16912 16878
    [21] 16848 16839 16901 16833 16896 16841 16735 16800 16781 16903
    

    所以正如@hrbrmstr所说,这只是一个单位的问题。

    我会留下这篇文章作为一个警告,以表明 POSIXct 类可能会产生意外的结果。我试图(不必要地)使用 scale_x_datetime 当时。

    推荐文章