【问题标题】:How could I set a year from a string with full date format?如何从具有完整日期格式的字符串中设置年份?
【发布时间】:2021-04-30 14:32:48
【问题描述】:

这听起来像是最基本的问题,但我宁愿继续它!

-这是一个闪亮的应用程序的一部分-

我读了一个 CSV 文件,其中一个列不再是 General,因为我习惯于看到它们,而是 Date 类型,我只关心那个完整日期的年份。它并不总是以相同的方式,这意味着有时它是 10/24/1995(月/日/年),而其他是 24/10/1995(日/月/年)。我正在使用lubridate 包来搭配以下简单的线条

df$File.Date <- mdy(df$File.Date)
df$year  <- lubridate::year(df$File.Date)

但是自从它开始为这个特定的字符串显示这种Date 格式后,它一直在下面说错误

Listening on http://127.0.0.1:6970
Warning: All formats failed to parse. No formats found.
Warning: Error in as.POSIXlt.character: character string is not in a standard unambiguous format
  152: stop
  151: as.POSIXlt.character
  149: year.default
  147: eventReactiveHandler [C:\Users\Melania CB\Documents\My time\Shiny app\Modeling app/server.R#121]
  103: df
  102: exprFunc [C:\Users\Melania CB\Documents\My time\Shiny app\Modeling app/server.R#132]
  101: widgetFunc
  100: func
   87: origRenderFunc
   86: renderFunc
   82: origRenderFunc
   81: output$new_date
    1: runApp

有时我可以在 Excel 中使用 Text to Columns 并在使用应用程序之前执行此操作,因此我不必更改 df$File.Date 但它开始做一些奇怪的事情,当我将其更改为 General 时输入它将10/31/2014 更改为41943,我什么都没有,有人可以带我走吗?

【问题讨论】:

    标签: r csv date shiny lubridate


    【解决方案1】:

    基于您只关心年份的观点,这里我提供了一个可重现的解决方案示例:

    x1 <-format(seq(today()-10,today()-5,by='day'),'%m/%d/%Y')
    x2 <- format(seq(today()-4,today(),by='day'), '%d/%m/%Y')
    df <- data.frame(x=c(x1,x2))
    
    df %>% separate(x,c('d1','d2','year')) %>% head()
    
       dm md year
    1  01 16 2021
    2  01 17 2021
    3  01 18 2021
    4  01 19 2021
    

    【讨论】:

      猜你喜欢
      • 2020-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-19
      • 1970-01-01
      相关资源
      最近更新 更多