Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 如何将月份和日期中没有前导零的字符转换为日期?_R_Date - Fatal编程技术网

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
from
anytime

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
??Id
11
天或月?第17个月或第26个月是哪一个月?您需要调整
format=
参数以匹配数据。