簡體   English   中英

日期為非標准格式時提取年月日

[英]Extract year, month and day when dates are non-standard format

我有一列日期,我想將年、月和日提取到單獨的列中。 不幸的是,日期列中的條目不一致,因此使用format(as.Date(),"%Y")lubridate::year()的正常解決方案不起作用。

這是一個示例 dataframe:

dates_df <- data.frame(dates = c("1985-03-23", "", "1983", "1984-01"))

這是期望的結果:

       dates year month  day
1 1985-03-23 1985     3   23
2            <NA>  <NA> <NA>
3       1983 1983  <NA> <NA>
4    1984-01 1984     1 <NA>

我可以使用以下代碼實現預期的結果,但在大型數據集(>100,000 行)上速度非常慢:

dates_df$year <- sapply(dates_df$dates, function(x) unlist(strsplit(x, "\\-"))[1])
dates_df$month <- sapply(dates_df$dates, function(x) unlist(strsplit(x, "\\-"))[2])
dates_df$day <- sapply(dates_df$dates, function(x) unlist(strsplit(x, "\\-"))[3])

我的問題:

有沒有更有效(快速)的方法從雜亂的日期數據中提取年、月、日列?

使用strsplit並調整length s。

cbind(dates_df, t(sapply(strsplit(dates_df$dates, '-'), `length<-`, 3)))
#        dates    1    2    3
# 1 1985-03-23 1985   03   23
# 2            <NA> <NA> <NA>
# 3       1983 1983 <NA> <NA>
# 4    1984-01 1984   01 <NA>

有好聽的名字:

cbind(dates_df, `colnames<-`(
  t(sapply(strsplit(dates_df$dates, '-'), `length<-`, 3)), c('year', 'month', 'day')))
#        dates year month  day
# 1 1985-03-23 1985    03   23
# 2            <NA>  <NA> <NA>
# 3       1983 1983  <NA> <NA>
# 4    1984-01 1984    01 <NA>

我的第一個想法是嘗試tidyr::separate 未經速度測試,如果示例數據中未顯示日期格式,則可能會崩潰。

tidyr::separate(dates_df, 
                dates, 
                into = c('year', 'month', 'day'), 
                remove = FALSE)

#-----
       dates year month  day
1 1985-03-23 1985    03   23
2                  <NA> <NA>
3       1983 1983  <NA> <NA>
4    1984-01 1984    01 <NA>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM