R 如何将月份和日期中没有前导零的字符转换为日期?
假设我得到一个向量,看起来像这样:R 如何将月份和日期中没有前导零的字符转换为日期?,r,date,R,Date,假设我得到一个向量,看起来像这样: dates <- c("2/11/2021","2/17/2021","2/26/2021","2/7/2021" ,"3/12/2021","3/18/2021","3/2/2021") #"2021-11-02" #"2021-02-17" #&q
dates <- c("2/11/2021","2/17/2021","2/26/2021","2/7/2021" ,"3/12/2021","3/18/2021","3/2/2021")
#"2021-11-02"
#"2021-02-17"
#"2021-02-16"
#"2021-07-02"
#"2021-12-03"
#"2021-18-03"
#"2021-02-03"
预期输出可能如下所示:
dates <- c("2/11/2021","2/17/2021","2/26/2021","2/7/2021" ,"3/12/2021","3/18/2021","3/2/2021")
#"2021-11-02"
#"2021-02-17"
#"2021-02-16"
#"2021-07-02"
#"2021-12-03"
#"2021-18-03"
#"2021-02-03"
是否有任何方法将所有元素转换为
.Date()
类?我们可以使用anydate
fromanytime
anytime::anydate(dates)
#[1] "2021-02-11"
#[2]"2021-02-17"
#[3] "2021-02-26"
#[4] "2021-02-07"
#[5] "2021-03-12"
#[6] "2021-03-18"
#[7] "2021-03-02"
使用
as.Date
,格式将是%m/%d/%Y
as.Date(dates, format = "%m/%d/%Y")
#[1] "2021-02-11" "2021-02-17" "2021-02-26" "2021-02-07" "2021-03-12" "2021-03-18" "2021-03-02"
第一个是2021-11-02
还是2021-02-11
??Id11
天或月?第17个月或第26个月是哪一个月?您需要调整format=
参数以匹配数据。