【问题标题】:unable to extract date, month and year in three separate columns from dataframe's "Date" column in the format "dd/mm/yyyy" or "dd/m/yyyy"无法从数据框“日期”列中以“dd/mm/yyyy”或“dd/m/yyyy”格式提取日期、月份和年份
【发布时间】:2021-11-17 10:08:45
【问题描述】:

我正在尝试使用

library(dplyr)
library(tidyr)
library(stringr)

# Dataframe has "Date" column and date in the format "dd/mm/yyyy" or "dd/m/yyyy"
df <- data.frame(Date = c("10/1/2001", "15/01/2010", "15/2/2010", "20/02/2010", "25/3/2010", "31/03/2010"))

# extract into three columns
df %>% extract(Date, c("Day", "Month", "Year"), "([^/]+), ([^/]+), ([^)]+)")

但上面的代码正在返回:

   Day Month Year
1 <NA>  <NA> <NA>
2 <NA>  <NA> <NA>
3 <NA>  <NA> <NA>
4 <NA>  <NA> <NA>
5 <NA>  <NA> <NA>
6 <NA>  <NA> <NA>

如何按预期正确提取结果中的日期:

   Day Month Year
1 10  1 2010
2 15  1 2010
3 15  2 2010
4 20  2 2010
5 25  3 2010
6 31  3 2010

【问题讨论】:

    标签: r dplyr tidyr stringr


    【解决方案1】:

    在这种情况下可能更容易使用separate

    df %>% 
      separate("Date", into=c("Day","Month","Year"), sep="/") %>% 
      mutate(Month=str_replace(Month, "^0",""))
    

    这将使所有内容都保留为字符值。如果您希望值是数字,请使用

    df %>% 
      separate("Date", into=c("Day","Month","Year"), sep="/", convert=TRUE)
    

    【讨论】:

    • 只有一个问题,如果我想以 01, 02, 03.... 11, 12, .... 30, 31 等格式保留月份和日期,是否可以在这里?
    • 使用第一个选项并跳过mutate() 步骤。这只是为了删除前导零。如果您想添加缺失的零,那么您可以使用以下选项之一:stackoverflow.com/questions/5812493/how-to-add-leading-zeros
    • 同意。但这将从 2010 年 15 月 1 日起将月份的格式保持为“1”,而不是“01”,不是吗?但实际上我想有“01”,而不是“1”。寻找解决方法:-)
    • 查看我上面的编辑以获取有关添加前导零的现有问题的链接。
    【解决方案2】:

    您的正则表达式模式已关闭。使用这个版本:

    df %>% extract(Date, c("Day", "Month", "Year"), "(\\d+)/(\\d+)/(\\d+)")
    

    【讨论】:

    • 谢谢蒂姆。这也真的很有帮助。感谢您纠正我的错误。
    【解决方案3】:

    我们可以使用lubridate:

    library(lubridate)
    library(dplyr)
    df %>% 
        mutate(Date = dmy(Date), # if your Date column is character type
               across(Date, funs(year, month, day)))
    
            Date Date_year Date_month Date_day
    1 2001-01-10      2001          1       10
    2 2010-01-15      2010          1       15
    3 2010-02-15      2010          2       15
    4 2010-02-20      2010          2       20
    5 2010-03-25      2010          3       25
    6 2010-03-31      2010          3       31
    

    【讨论】:

    • 谢谢 :) - 只是一个问题,如果我想以 01、02、03.... 11、12、.... 30、31 等格式保留月份和日期,这段代码有可能吗?还是需要其他一些调整?
    • 您可以添加mutate(Date_month_char = sprintf("%02d", Date_month))。这将为您提供一个字符列。或者,如果您希望月份名称缩写:mutate(Date_month_abbr = month(Date_month, label = TRUE))
    【解决方案4】:

    我们可以使用来自base Rread.table

    read.table(text = df$Date, sep="/", header = FALSE, 
         col.names = c("Day", "Month", "Year"))
      Day Month Year
    1  10     1 2001
    2  15     1 2010
    3  15     2 2010
    4  20     2 2010
    5  25     3 2010
    6  31     3 2010
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-02
      • 1970-01-01
      • 1970-01-01
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      • 2019-10-12
      • 2019-01-20
      相关资源
      最近更新 更多