【问题标题】:merge list changes date format to numeric合并列表将日期格式更改为数字
【发布时间】:2018-02-19 15:10:11
【问题描述】:

我有长度为 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))

【问题讨论】:

  • 请阅读有关how to ask a good question 的信息以及如何提供reproducible example。这将使其他人更容易帮助您。
  • @user3734568 我已经编辑了您的答案,以便您列表中的日期为Date 格式
  • 发生这种情况是因为do.call(rbind, ...) 将您的对象强制转换为矩阵。由于矩阵不需要属性,因此诸如 POSIXct 或因子之类的类被简化为它们的数值。

标签: r list merge data-manipulation


【解决方案1】:

您可以使用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"
)))

我已编辑您的帖子,以便您在列表中的日期为 Date 格式

【讨论】:

    【解决方案2】:

    使用base 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-01
      • 2022-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-03
      相关资源
      最近更新 更多