在R中转换文本日期

时间:2017-10-09 19:43:45

标签: r date

我有数据格式化日期:

Tue Oct 25 2016
Tue Oct 25 2016
Tue Oct 25 2016
Wed Oct 26 2016
Wed Oct 26 2016
Wed Oct 26 2016

我希望这种格式可以R将其用作日期(即2016-10-25)。有什么帮助吗?

3 个答案:

答案 0 :(得分:6)

修改: 我不知道你错过了一周的哪一天。

这也可以使用as.Date和正确的格式字符串在base中完成。在这种情况下%a将为您提供一周中的缩写日期,%B将为您提供月份缩写,%d将为您提供最小数字日(即2而不是02),并且%Y会给你四位数的年份。在示例中,这些都由单个空格分隔,因此格式字符串应该反映出来。

datesx <- c("Tue Oct 25 2016", "Tue Oct 25 2016", "Wed Oct 26 2016", "Wed Oct 26 2016", "Wed Oct 26 2016", "Wed Oct 26 2016")
as.Date(datesx,format = "%a %B %d %Y")

[1] "2016-10-25" "2016-10-25" "2016-10-26" "2016-10-26" "2016-10-26" "2016-10-26"

答案 1 :(得分:2)

anytime包有anydate()这是非常好的,并尝试了许多不同的格式。在这里,我们仍然需要切断(多余的)工作日:

R> library(anytime)
R> anydate(c("Oct 25 2016", "Oct 25 2016", "Oct 25 2016", 
+          "Oct 26 2016", "Oct 26 2016", "Oct 26 2016"))
[1] "2016-10-25" "2016-10-25" "2016-10-25" 
[4] "2016-10-26" "2016-10-26" "2016-10-26"
R> 

答案 2 :(得分:0)

这个答案不使用额外的包:

dates <- c("Tue Oct 25 2016",
       "Tue Oct 25 2016",
       "Tue Oct 25 2016",
       "Wed Oct 26 2016",
       "Wed Oct 26 2016",
       "Wed Oct 26 2016")

# Remove day of the week
dates <- sub("\\w{3} ", "", dates)

# Convert to Date
dates <- as.Date(dates, "%b %d %Y", origin = "1970-01-01")
dates
#[1] "2016-10-25" "2016-10-25" "2016-10-25" "2016-10-26" "2016-10-26" 
# "2016-10-26"