R日期格式 - 将字符串转换为日期

时间:2015-05-04 06:07:40

标签: r date format

我正在尝试从数据框中读取日期列,该数据框存储为字符串|(参见列' DateString'。这就是我的数据的样子:

  X. Date_String       ASIN Stars positive_rating
1  0    20150430 B00GKKI4IE     5               0
2  1    20150430 B00GKKI4IE     5               0
3  2    20150430 B00GKKI4IE     5               0
4  3    20150429 B00GKKI4IE     5               0
5  4    20150428 B00GKKI4IE     5               0
6  5    20150428 B00GKKI4IE     5               0

这就是我用来格式化这个列的日期

data$date.of.review  <- as.Date(data$Date_String, "%Y%m%d")

并收到错误消息

Error in charToDate(x) : 
  character string is not in a standard unambiguous format

任何想法如何解决?感谢

以下是数据帧的结构:

structure(list(X. = 0:5, Date_String = c(20150430L, 20150430L, 
20150430L, 20150429L, 20150428L, 20150428L), ASIN = structure(c(1L, 
1L, 1L, 1L, 1L, 1L), .Label = c("B00GKKI4IE", "B00I4OBXWI", "B00IB17BFM", 
"B00IN2WD5C", "B00J58F0IA", "B00K7NCS9G", "B00KJEZIBS", "B00KZER5GS", 
"B00MK39H68", "B00O1GTTWY"), class = "factor"), Stars = c(5L, 
5L, 5L, 5L, 5L, 5L), positive_rating = c(0, 0, 0, 0, 0, 0)), .Names = c("X.", 
"Date_String", "ASIN", "Stars", "positive_rating"), row.names = c(NA, 
6L), class = "data.frame")

1 个答案:

答案 0 :(得分:2)

如果将变量包装在as.character中,则该类为整数.date可以读取它。

sapply(data, class)
data$date.of.review  <- as.Date(as.character(data$Date_String), "%Y%m%d")
data