为什么 data.frame 不会将列类型 'unknown' 转换为日期?

Why will data.frame not convert column type 'unknown' to date?

栈友溢出, 我有一段时间让我的假 data.frame 转换为 class 类型 'date'.

数据

library(anytime)

fake.data<-data.frame(
  
  date = c('01/01/2019', '01/02/2019', '01/03/2019', '01/04/2019', '01/05/2019', '01/06/2019', '01/07/2019',
           '01/01/2019', '01/02/2019', '01/03/2019', '01/04/2019', '01/05/2019', '01/06/2019', '01/07/2019'),
  
  location = c('Point A', 'Point A', 'Point A', 'Point A', 'Point A', 'Point A', 'Point A',
               'Point B', 'Point B', 'Point B', 'Point B', 'Point B', 'Point B', 'Point B'
  ),
  
  vehicle = c('ZZ12', 'ZZ12', 'AA12', 'AA12', 'AA12', 'AA12', 'ZZ12',
              'ZZ12', 'ZZ12', 'AA12', 'AA12', 'AA12', 'AA12', 'ZZ12'),
  
  count = c(2, 1, 4, 4, 3, 4, 2,
            3, 3, 1, 1, 5, 6, 6),
  stringsAsFactors = FALSE)

The structure returns:

>str(fake.data$date)
 chr [1:14] "01/01/2019" "01/02/2019" "01/03/2019" "01/04/2019" "01/05/2019" "01/06/2019" "01/07/2019" "01/01/2019" "01/02/2019" ...

我尝试将 class 类型更改为 'Date' 的尝试仍然失败。例如:

fake.data$date<- anydate(fake.data$date)

Returns:

> head(str(fake.data))
'data.frame':   14 obs. of  4 variables:
 $ date    : Date, format: "2019-01-01" "2019-01-02" "2019-01-03" "2019-01-04" ...
 $ location: chr  "Point A" "Point A" "Point A" "Point A" ...
 $ vehicle : chr  "ZZ12" "ZZ12" "AA12" "AA12" ...
 $ count   : num  2 1 4 4 3 4 2 3 3 1 ...

这看起来不错,但是当我尝试将其用于可视化(即绘图)时,我得到了我认为的 as.POSIXct:

The date no longer renders in the format..just changes in to this odd numeric. Any ideas?

我也试过as.Dateas.character(as.Date(...)),都没有用。奇怪的是..图表底部的日期仍然呈现正确的格式。

应用程序副本

ui<- shinyUI(
  fluidPage(
    plotOutput("plotthis", hover="clickthis"),    
    tableOutput("rawdata")                      
  )
)
server<- shinyServer(function(input,output) {

  output$plotthis<- renderPlot({
    
    ggplot(fake.data,aes(x=date, y=vehicle)) +
      geom_point()
  })
  
  output$rawdata<- renderTable({  
    nearPoints(fake.data,input$clickthis, threshold = 10)   
  })
})
shinyApp(ui, server)

试试这个:

library(lubridate)
fake.data$new_date <- dmy(fake.data$date)