合并列表将日期格式更改为数字

merge list changes date format to numeric

我有长度为 18 的列表,当我尝试合并这些列表以创建数据框时,它会将日期格式更改为数字。

我使用了以下语法

forecast_data = do.call(rbind, datalist)

当我执行上面的代码时,有 3 个日期列全部更改为数字。

有没有一种方法可以在合并列表时将日期列的类型保留为仅日期。请指教。

请参考下面的示例列表和我想从一组列表中获得的结果

datalist = list()

l <- data.frame(ID=c(1), Date=as.Date("2017-07-02"), Prediction=c(66))
l <- as.list(l)
datalist[[1]] <- (l)

l <- data.frame(ID=c(1), Date=as.Date("2017-07-09"), Prediction=c(70))
l <- as.list(l)
datalist[[2]] <- (l)

l <- data.frame(ID=c(1), Date=as.Date("2017-07-16"), Prediction=c(77))
l <- as.list(l)
datalist[[3]] <- (l)


result <- data.frame(ID=c(1,1,1), Date=c("2017-07-02","2017-07-09","2017-07-16"), Prediction=c(66,70,77))

您可以使用 data.table 包中的 rbindlist

library(data.table)
ans <- rbindlist(datalist)

输出

   ID       Date Prediction
1:  1 2017-07-02         66
2:  1 2017-07-09         70
3:  1 2017-07-16         77

str(ans)

Classes ‘data.table’ and 'data.frame':  3 obs. of  3 variables:
 $ ID        : num  1 1 1
 $ Date      : Date, format: "2017-07-02" "2017-07-09" ...
 $ Prediction: num  66 70 77

数据

datalist <- list(structure(list(ID = 1, Date = structure(17349, class = "Date"), 
Prediction = 66), .Names = c("ID", "Date", "Prediction")), 
structure(list(ID = 1, Date = structure(17356, class = "Date"), 
    Prediction = 70), .Names = c("ID", "Date", "Prediction"
)), structure(list(ID = 1, Date = structure(17363, class = "Date"), 
    Prediction = 77), .Names = c("ID", "Date", "Prediction"
)))

我已经编辑了你的post,所以你在列表中的日期是Date格式

使用基础 R 可以使用 Reducedo.call

  Reduce(rbind,Map(do.call,c(cbind.data.frame),datalist))
   ID       Date Prediction
 1  1 2017-07-02         66
 2  1 2017-07-09         70
 3  1 2017-07-16         77

  do.call(rbind,Map(do.call,c(cbind.data.frame),datalist))
   ID       Date Prediction
 1  1 2017-07-02         66
 2  1 2017-07-09         70
 3  1 2017-07-16         77

结果类:

  str(do.call(rbind,Map(do.call,c(cbind.data.frame),datalist)))
 'data.frame':  3 obs. of  3 variables:
  $ ID        : num  1 1 1
  $ Date      : Date, format: "2017-07-02" "2017-07-09" ...
  $ Prediction: num  66 70 77