R将字符串向量转换为具有异常日期格式的日期

时间:2014-08-26 08:25:49

标签: r date

我正在尝试将因子矢量转换为R中的日期向量。我知道关于这个主题有很多问题,但是我找不到关于如何转换这种特定类型的向量的答案。

数据和我的尝试如下:

dates <- c(1/4/2005, 1/5/2005, 1/6/2005, 1/7/2005, 1/8/2005, 1/9/2005, 1/10/2005)
class(dates)
 "factor"
dates <- as.character(dates)
class(dates)
 "character"

然后我尝试了两种方法,使用以下方法将此字符串格式转换为日期格式:

dates <- as.date(dates)  #This converts the vector to 0001-04-20, 0001-11-20, NA, NA, 0002-01-20,..
dates <- strptime(dates, "%m/%d/%y")  #This converts the vector to 2020-01-04, 2020-01-02, ...

我认为这是因为日期列保存了每个月和每天的单个数字,例如白天为“1”而不是“01”,当天为“5”而不是“05”。有没有办法将此字符向量转换为正确的日期格式?谢谢。

2 个答案:

答案 0 :(得分:0)

问题1:您的日期是数字,即1/4/2005等于(1/4)/ 2005 = 1.24E-4

问题2:您需要4个数字年的“%Y”(%y是2位数年)

这应该有效:

dates <- c("1/4/2005", "1/5/2005", "1/6/2005", "1/7/2005", "1/8/2005", "1/9/2005", "1/10/2005")
strptime(dates, "%m/%d/%Y")

答案 1 :(得分:0)

我假设您的日期是短日期格式(可能来自Excel),这是我从大多数时间将数据从excel导出到csv并通过read.csv读入R时遇到的。

dates <- c("1/4/2005", "1/5/2005", "1/6/2005", "1/7/2005", "1/8/2005")
df <- data.frame(dates = dates) # emulate df = read.csv(file)

然后,您希望通过

将日期列添加到df
df$Date <- as.Date(df$dates, format="%m/%d/%Y")    
df
     dates       Date
1 1/4/2005 2005-01-04
2 1/5/2005 2005-01-05
3 1/6/2005 2005-01-06
4 1/7/2005 2005-01-07
5 1/8/2005 2005-01-08

然后,您可以使用Date列进行时间序列操作,例如通过xts。

相关问题