【问题标题】:R convert string "Jan\n1990" to date formatR将字符串“Jan\n1990”转换为日期格式
【发布时间】:2020-05-12 04:28:23
【问题描述】:

我有一个 csv 文件,其中第一列(名为“月”)具有月份数据格式 “Jan\n1990”、“Feb\n1990”等等。 当我使用 read.csv 函数(使用 stringsAsFactors = FALSE)读取 R 中的文件时,它将“月”列读取为“chr”。我想把它转换成日期格式。我试过了

month_1 <- as.Date(f4$month)

但它给出了错误

Error in charToDate(x) : 
  character string is not in a standard unambiguous format

如何将第一列转换为日期格式的列?

【问题讨论】:

  • 日期需要几天...所以你必须提供它和当前变量。使用paste(..., collapse="...") 并从?strftime 中计算出所需的格式。
  • 是的,这绝对是您可以在 Python 中完成的事情。请参阅datetime 模块。

标签: r datetime


【解决方案1】:

另一个选项是as.yearmon 来自zoo

library(zoo)
as.Date(as.yearmon(date))
#[1] "1990-01-01" "1990-02-01"

【讨论】:

    【解决方案2】:

    基于as.Date的解决方案:

    date <- c("Jan\n1990","Feb\n1990") 
    
    as.Date(paste0("1",date), format="%d%b\n%Y")
    # [1] "1990-01-01" "1990-02-01"
    

    【讨论】:

      【解决方案3】:

      r 中,使用lubridate 包中的函数parse_date_time,可以将字符串转换为日期格式:

      date <- c("Jan\n1990","Feb\n1990") # Example of character strings to convert into dates
      
      library(lubridate)
      parse_date_time(date, order = "bY")
      
      [1] "1990-01-01 UTC" "1990-02-01 UTC"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-26
        • 1970-01-01
        • 1970-01-01
        • 2013-12-28
        • 1970-01-01
        • 1970-01-01
        • 2014-01-18
        相关资源
        最近更新 更多