R date format - cast string as date [duplicate]

我怕爱的太早我们不能终老 提交于 2020-07-24 04:08:30

问题


I am trying to read a date column from a dataframe, which is stored as a string |(see column 'DateString'. This is how my data looks like:

  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

and this is what I am using to format this column as Date

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

and getting an error message

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

any ideas how to solve it? thanks

Here is the structure of the dataframe:

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:


The class is integer if you wrap the variable in as.character as.date can read it.

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


来源:https://stackoverflow.com/questions/30023578/r-date-format-cast-string-as-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!