我如何从具有完整日期格式的字符串中设置年份?

How could I set a year from a string with full date format?

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

-这是 Shiny App 的一部分-

我读了一个 CSV 文件,其中一列不再是 General,因为我习惯看到它们,而是 Date 类型,我只关心那个完整日期的年份。它并不总是以相同的方式显示,这意味着有时它是 10/24/1995 (month/day/year) 和其他它是 24/10/1995 (day/month/year)。我正在使用 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,但我什么也没得到,有人可以指导我吗?

基于你只关心年份这一点,这里我有一个可重现的例子和解决方案:

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