【问题标题】:Date format changes using read_xlsx function within reactive environment in R shiny在 R 闪亮的反应环境中使用 read_xlsx 函数更改日期格式
【发布时间】:2018-11-09 12:16:08
【问题描述】:

我使用 R 创建了以下数据框

datelist<-seq(as.Date('2011-01-01'),as.Date('2011-01-31'),by = 1)

df<-as.data.frame(datelist)
df$New<-1:nrow(df)

接下来我创建了一个 UI 和服务器,使用 shiny 来读取表格

library(shiny)
UI<-fluidPage(fileInput("file", "Browse",
                    accept = c("text/csv",
                               "text/comma-separated-values,text/plain",
                               ".csv")),dateInput(inputId = "Cutoffdate", 
    label = "Cut Off Date"),
          tableOutput(outputId = "Table1"))

Server<-function(input, output, session){

   options(shiny.maxRequestSize=100*1024^2) 

   output$Table1<-renderTable({

   infile <- input$file
   if (is.null(infile)) {
   # User has not uploaded a file yet
   return(NULL)
   }

    df<-readxl::read_xlsx(input$file$datapath)
   })

shinyApp(UI, Server)

表格输出给出了一系列数字,而不是年份月份日期。我曾尝试使用 lubridate 的 ymd 但这没有帮助。有没有办法在 R

的反应性环境中将数据哄骗到 ymd

【问题讨论】:

  • 如果您将列类型设为日期,Excel 可能会将日期存储为整数。它有自己的格式并且可能会改变。我建议将日期存储为字符串,并在 R 中使用as.Date 进行转换
  • df 创建后是否将其导出到 excel/csv?然后用 R 读回来?
  • @VisheshShrivastav 是的。但即使在外部存储为日期,它也只会产生这个

标签: r shiny readxl


【解决方案1】:

由于您的 fileInput 仅接受 .csv 格式,我建议使用 read.table 来读取数据。您可以使用read.table 函数中的colClasses 参数指定列格式。

df <- read.table(input$file$datapath, header = TRUE, sep = ","
                 colClasses = c("Date", "factor" # ... etc
                 ))
    )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 2022-10-31
    • 2014-05-15
    • 2013-12-22
    • 2021-01-04
    • 2018-02-17
    • 1970-01-01
    相关资源
    最近更新 更多