简体   繁体   English

为什么data.frame不能将列类型“未知”转换为日期?

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

Friends of stack overflow , I am having a heck of a time getting my fake data.frame to convert to class type 'date'. 堆栈溢出之友,我真想让我的假data.frame转换为类类型“ date”。

Data 数据

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" ...

My attempts to change the class type to 'Date' continue to fail. 我将类类型更改为“日期”的尝试仍然失败。 For example: 例如:

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 ...

This seems great, but when I try to utilize this for visualization (ie plots), I get what I think are as.POSIXct: 这似乎很棒,但是当我尝试将其用于可视化(即绘图)时,我得到了我认为的样子。POSIXct:

交互式悬停图的屏幕截图

The date no longer renders in the format..just changes in to this odd numeric. 日期不再以格式显示。只是更改为该奇数。 Any ideas? 有任何想法吗?

I have also tried as.Date , as.character(as.Date(...)) , to no avail. 我也尝试了as.Dateas.character(as.Date(...)) ,无济于事。 Oddly..the date on the bottom of the chart still renders the correct format. 奇怪的是..图表底部的日期仍然呈现正确的格式。

Copy of the app 应用程序副本

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)

Try this : 尝试这个 :

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM