代码之家  ›  专栏  ›  技术社区  ›  user3734568

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

  •  1
  • user3734568  · 技术社区  · 7 年前

    我使用了以下语法

    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))
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   CPak    7 年前

    rbindlist 从…起 data.table 包裹

    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
  •  1
  •   Onyambu    7 年前

    使用base R可以使用 Reduce do.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