简体   繁体   English

在R中转换为日期格式时出错

[英]Error while converting to Date format in R

It should be an easy issue, but I got stacked with it. 这应该是一个简单的问题,但是我对此感到困惑。 I have a data.frame with dates and values: 我有一个日期和值的data.frame:

    class(var_data)
    [1] "tbl_df"     "tbl"        "data.frame"
    var_data
    A tibble: 42 x 2
       date                Tourists
       <dttm>                 <dbl>
     1 2006-03-01 00:00:00   55280.
     2 2006-06-01 00:00:00   84392.
     3 2006-09-01 00:00:00  132714.

Then I want to copy some dates and values into other data.frame: 然后我想将一些日期和值复制到其他data.frame中:

    var_list_DB$var_last[ii] <- var_data[last,"Tourists"]
    var_list_DB$var_date_start[ii] <- var_data[1,"date"]
    var_list_DB$var_date_last[ii] <- var_data[last,"date"] 

But instead of dates I got numbers: 但是我没有日期,而是数字:

    var_date_start   var_date_last  var_val_last 
    951868800        1496275200      10044.3162

And while trying to convert to date format, got an error: 并且在尝试转换为日期格式时,出现错误:

    as.Date(var_data[last,"date"], format = "%m/%d/%Y")
    Error in as.Date.default(x, ...) : 
      do not know how to convert 'x' to class “Date”

I recently updated to 3.5.0 version, may be this is an issue. 我最近更新到3.5.0版本,可能是一个问题。

Add as.character convertion before pass to date and move var_data to data.frame format, like this two examples using as.Date and as.POSIXct : 在传递日期之前添加as.character转换,并将as.character转换为data.frame格式,如下面两个使用as.Dateas.POSIXct示例as.POSIXct

var_data<-data.frame(var_data)
as.Date(as.character(var_data[,"date"]))
[1] "2006-03-01" "2006-06-01" "2006-09-01"
as.POSIXct(as.character(var_data[,"date"]))
[1] "2006-03-01 CET"  "2006-06-01 CEST" "2006-09-01 CEST"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM