简体   繁体   中英

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:

    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:

    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.

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 :

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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