【问题标题】:R date format - cast string as date [duplicate]R日期格式-将字符串转换为日期[重复]
【发布时间】:2015-05-04 06:07:39
【问题描述】:

我正在尝试从存储为字符串的数据框中读取日期列|(请参阅列“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")

【问题讨论】:

  • as.Date("20150430", "%Y%m%d") 似乎有效。您确定“Date_String”是字符串而不是数值吗?你的data.frame的结构到底是什么。如how to make a great reproducible example 中所述包含dput() 怎么样。
  • 如果您使用library(lubridate),它也会采用数值。 IE。 ymd(data$Date_String)#[1] "2015-04-30 UTC" "2015-04-30 UTC" "2015-04-30 UTC" "2015-04-29 UTC" [5] "2015-04-28 UTC" "2015-04-28 UTC" 否则,正如@MrFlick 提到的,将列转换为字符。即as.Date(as.character(data$Date_String), format="%Y%m%d")

标签: r date format


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-16
    相关资源
    最近更新 更多