不知道如何将“ x”转换为“日期”类

时间:2020-11-09 03:00:49

标签: r

我正在用R编写此代码,但无法解决此错误。

L <- read_csv('C:\\Users\\Documents\\LaptopSales.csv',col_names = TRUE)
Dates=as.Date(L[,2],format = "%m/%d/%Y")    <--- this keeps me showing an error
tab=data.frame(Dates,L$Retail.Price)
tab$Month=as.Date(cut(Dates,breaks="month"))
head(tab$Month)

输出

Parsed with column specification:
cols(
  Date = col_character(),
  Configuration = col_double(),
  `Customer Postcode` = col_character(),
  Store.Postcode = col_character(),
  Retail.Price = col_double(),
  `Screen Size (Inches)` = col_double(),
  `Battery Life (Hours)` = col_double(),
  `RAM (GB)` = col_double(),
  `Processor Speeds (GHz)` = col_double(),
  `Integrated Wireless?` = col_character(),
  `HD Size (GB)` = col_double(),
  `Bundled Applications?` = col_character(),
  `customer X` = col_double(),
  `customer Y` = col_double(),
  `store X` = col_double(),
  `store Y` = col_double()
)

as.Date.default(x,...)中的错误:不知道如何将'x'转换为类“ Date”

数据

dput(head(L))

structure(list(Date = c("1/1/2008 0:01", "1/1/2008 0:02", "1/1/2008 0:04", 
"1/1/2008 0:04", "1/1/2008 0:06", "1/1/2008 0:12"), Configuration = c(163, 
320, 23, 169, 365, 309), `Customer Postcode` = c("EC4V 5BH", 
"SW4 0JL", "EC3V 1LR", "SW1P 3AU", "EC4V 4EG", "W1B 5PX"), Store.Postcode = c("SE1 2BN", 
"SW12 9HD", "E2 0RY", "SE1 2BN", "SW1V 4QQ", "SW1V 4QQ"), Retail.Price = c(455, 
545, 515, 395, 585, 555), `Screen Size (Inches)` = c(15, 15, 
15, 15, 15, 15), `Battery Life (Hours)` = c(5, 6, 4, 5, 6, 6), 
    `RAM (GB)` = c(1, 1, 1, 1, 2, 1), `Processor Speeds (GHz)` = c(2, 
    2, 2, 2, 2, 2), `Integrated Wireless?` = c("Yes", "No", "Yes", 
    "No", "No", "Yes"), `HD Size (GB)` = c(80, 300, 300, 40, 
    120, 120), `Bundled Applications?` = c("Yes", "No", "Yes", 
    "Yes", "Yes", "Yes"), `customer X` = c(532041, 529240, 533095, 
    529902, 531684, 529207), `customer Y` = c(180995, 175537, 
    181047, 179641, 180948, 180969), `store X` = c(534057, 528739, 
    535652, 534057, 528924, 528924), `store Y` = c(179682, 173080, 
    182961, 179682, 178440, 178440)), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"))

不确定如何解决此问题。我查看了所有其他在线可用的解决方案,但无法修复它。 请帮忙。谢谢

3 个答案:

答案 0 :(得分:0)

您可以使用as.Date

L$Date <- as.Date(L$Date, '%m/%d/%Y %H:%M')

答案 1 :(得分:0)

我遇到了类似的错误,将其复制到另一个变量中对我有帮助。我不确定这是否对您有帮助。您可以尝试一下。

a <- L$Date
Dates <- as.Date(a,format = "%m/%d/%Y")
month <- as.Date(cut(Dates,breaks="month"))

答案 2 :(得分:0)

我们可以使用lubridate

 library(lubridate)
 L$Date <- mdy_hm(L$Date)