[英]How to convert a date in the format dd-mm-yyyy hh:mm into yyyy-mm-dd in R
[英]How would I transform minute date ( MM/DD/YYYY HH:MM) into the format (MM/DD/YYYY)
由於標題已經 state 我正在處理以下格式的分鍾數據:
head(data$time)
[1] "11/10/2019 12:20" "10/10/2019 13:10" "03/01/2020 13:12" "11/10/2018 17:46"
我想理想地從條目中省略 HH:MM,並且想知道最有效的方法是什么。
一種可能的解決方案, anytime
使用 package :
anytime::anydate("11/10/2019 12:20")
#> [1] "2019-11-10"
使用as.Date
的基本 R 方法將返回日期 class。
x <- c("11/10/2019 12:20", "10/10/2019 13:10", "03/01/2020 13:12", "11/10/2018 17:46")
as.Date(x, '%m/%d/%Y')
#[1] "2019-11-10" "2019-10-10" "2020-03-01" "2018-11-10"
如果您想要用於mm/dd/yyyy
的 output,您將返回字符 class。
您可以使用format
format(as.Date(x, '%m/%d/%Y'), '%m/%d/%Y')
#[1] "11/10/2019" "10/10/2019" "03/01/2020" "11/10/2018"
或者在空間之后放下所有東西。
sub('\\s.*', '', x)
#[1] "11/10/2019" "10/10/2019" "03/01/2020" "11/10/2018"
使用 lubridate package 您必須解析日期時間格式( lubridate::mdy_hm
),然后您只能提取日期部分( as_date
):
d <- "11/10/2019 12:20"
lubridate::as_date(lubridate::mdy_hm(d))
“2019-11-10”
lubridate::as_date(d)
只是不行,它給出“2011-10-20”
底座 R:
# Remove everything after space you will get character format
dates <- sub(" .*", "", data$time)
dates
# [1] "11/10/2019" "10/10/2019" "03/01/2020" "11/10/2018"
# to transform to date class use as.Date
as.Date(dates, format = "%m/%d/%Y")
# [1] "2019-11-10" "2019-10-10" "2020-03-01" "2018-11-10"
數據:
df <- structure(list(time = c("11/10/2019 12:20", "10/10/2019 13:10",
"03/01/2020 13:12", "11/10/2018 17:46")), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -4L))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.