【问题标题】:Extracting "Year" , "Month" and "Day" from Date column which is in continuous string format从连续字符串格式的日期列中提取“年”、“月”和“日”
【发布时间】:2021-02-01 01:34:41
【问题描述】:

您好,我有一个格式如下所示的数据框:

structure(list(ID = c(1, 2, 3, 4, 5, 6, 7), Date = c("20200230", 
"20200422", "20100823", "20190801", "20130230", "20160230", "20150627"
)), class = "data.frame", row.names = c(NA, -7L))

  ID     Date
1  1 20200230
2  2 20200422
3  3 20100823
4  4 20190801
5  5 20130230
6  6 20160230
7  7 20150627

日期列中的日期不是标准格式,而是以yyyymmdd 形式显示。如何从Date 列中分离年、月和日,并将它们另存为数据框中的单独新列,结果如下所示?

  ID     Date   Year  Month  Day
1  1 20200230   2020   02     30
2  2 20200422   2020   04     22
3  3 20100823  ....................
4  4 20190801  ....................
5  5 20130230  ....................
6  6 20160230  ....................
7  7 20150627  ....................

我尝试使用format(as.Date(x, format="%YYYY%mm/%dd"),"%YYYY"),但它对我不起作用。我还尝试了以下代码:

Data$Year <- year(ymd(Data$Date))

结果是这样的形式:

  ID     Date Year
1  1 20200230   NA
2  2 20200422 2020
3  3 20100823 2010
4  4 20190801 2019
5  5 20130230   NA
6  6 20160230   NA
7  7 20150627 2015

正如@neilfws 所述,我得到 NA 的原因是日期无效;但是,我真的不在乎有效性,无论如何我都想提取年份。

【问题讨论】:

  • 你得到 NA 因为没有 2 月 30 日。
  • @neilfws。有什么办法可以防止这个错误?我不在乎这一天,我想要的只是“年”
  • 我不会说这是一个错误。这是函数尝试解析无效日期时的预期结果。

标签: r date


【解决方案1】:

如果您只想要年份而不关心日期验证,最简单的解决方案可能是从 Date 中提取前 4 个字符并转换为数字。

Data$Year <- as.numeric(substring(Data$Date, 1, 4))

Date 进行某种检查可能会很好,例如它们都包含 8 位数字。

【讨论】:

    【解决方案2】:

    一个表达式中的基础 R:

    # If you want to keep the Date vector: 
    cbind(df, 
      strcapture(pattern = "^(\\d{4})(\\d{2})(\\d{2})$",
        x = df$Date,
        proto = list(year = integer(), month = integer(), day = integer())))
    
    # If you want to drop the Date vector: 
    cbind(within(df, rm(Date)),
          strcapture(pattern = "^(\\d{4})(\\d{2})(\\d{2})$",
            x = df$Date,
            proto = list(year = integer(), month = integer(), day = integer())))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-19
      • 2021-12-05
      • 2021-08-14
      • 2016-07-27
      • 1970-01-01
      • 1970-01-01
      • 2020-04-29
      • 2017-10-28
      相关资源
      最近更新 更多