我有以下日期。
c("Aug 08, 2017", "Aug 09, 2017", "Aug 11, 2017", "Aug 11, 2017",
"Aug 10, 2017", "Sep 22, 2017", "Aug 11, 2017", "Aug 11, 2017",
"Aug 11, 2017", "Aug 14, 2017", "Aug 16, 2017", "Aug 16, 2017",
"Aug 18, 2017", "Aug 18, 2017", "Aug 18, 2017", "Sep 20, 2017",
"Aug 22, 2017", "Sep 20, 2017", "Sep 14, 2017", "Sep 25, 2017"
)
我正在尝试将它们转换为以下格式:
structure(c(17386, 17387, 17388, 17389, 17392, 17393, 17394,
17395, 17396, 17399, 17400, 17401, 17402, 17403, 17406, 17407,
17408, 17409, 17410, 17414), class = "Date")
看起来像什么
[1] "2017-08-08" "2017-08-09" "2017-08-10" "2017-08-11" "2017-08-14" "2017-08-15" "2017-08-16" "2017-08-17"
[9] "2017-08-18" "2017-08-21" "2017-08-22" "2017-08-23" "2017-08-24" "2017-08-25" "2017-08-28" "2017-08-29"
[17] "2017-08-30" "2017-08-31" "2017-09-01" "2017-09-05"
如何将字符转换为日期格式?
编辑:
我运行以下内容;
> C=c("Aug 08, 2017", "Aug 09, 2017", "Aug 11, 2017", "Aug 11, 2017",
+ "Aug 10, 2017", "Sep 22, 2017", "Aug 11, 2017", "Aug 11, 2017",
+ "Aug 11, 2017", "Aug 14, 2017", "Aug 16, 2017", "Aug 16, 2017",
+ "Aug 18, 2017", "Aug 18, 2017", "Aug 18, 2017", "Sep 20, 2017",
+ "Aug 22, 2017", "Sep 20, 2017", "Sep 14, 2017", "Sep 25, 2017"
+ )
> as.numeric(as.Date(C,format='%B %d, %Y'))
[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
> as.Date(C,format='%B %d, %Y')
[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
编辑: 以下内容也不起作用;
date <- gsub(",", "", date)
date <- gsub(" ", "-", date)
date
as.numeric(as.Date(date, format='%b %d, %Y'))
编辑:
以下似乎有效;
mdy(C)
给予;
[1] "2017-08-08" "2017-08-09" "2017-08-11" "2017-08-11" "2017-08-10" "2017-09-22" "2017-08-11" "2017-08-11"
[9] "2017-08-11" "2017-08-14" "2017-08-16" "2017-08-16" "2017-08-18" "2017-08-18" "2017-08-18" "2017-09-20"
[17] "2017-08-22" "2017-09-20" "2017-09-14" "2017-09-25"
答案 0 :(得分:0)
您需要使用format
中的as.Date
as.numeric(as.Date(C,format='%B %d, %Y'))
[1] 17386 17387 17389 17389 17388 17431 17389 17389 17389 17392 17394 17394 17396 17396 17396 17429 17400 17429 17423 17434
as.Date(C,format='%B %d, %Y')
[1] "2017-08-08" "2017-08-09" "2017-08-11" "2017-08-11" "2017-08-10" "2017-09-22" "2017-08-11" "2017-08-11" "2017-08-11" "2017-08-14" "2017-08-16"
[12] "2017-08-16" "2017-08-18" "2017-08-18" "2017-08-18" "2017-09-20" "2017-08-22" "2017-09-20" "2017-09-14" "2017-09-25"
Dinput:
C=c("Aug 08, 2017", "Aug 09, 2017", "Aug 11, 2017", "Aug 11, 2017",
"Aug 10, 2017", "Sep 22, 2017", "Aug 11, 2017", "Aug 11, 2017",
"Aug 11, 2017", "Aug 14, 2017", "Aug 16, 2017", "Aug 16, 2017",
"Aug 18, 2017", "Aug 18, 2017", "Aug 18, 2017", "Sep 20, 2017",
"Aug 22, 2017", "Sep 20, 2017", "Sep 14, 2017", "Sep 25, 2017"
)