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

阿尔宾德。数据框架将日期转换为数字

  •  0
  • Denis  · 技术社区  · 6 年前

    我在努力理解为什么 rbind.data.frame 将日期转换为数字格式,以及如何修复。假设我有以下几点:

    v <- list(
              row1=list(col1 = as.Date("2011-01-23"), col2="A"), 
              row2=list(col1 = as.Date("2012-03-03"), col2="B"))
    

    现在我试着做:

    df <- do.call(rbind.data.frame, v)
    str(df)
    'data.frame':   2 obs. of  2 variables:
     $ col1: num  14997 15402
     $ col2: Factor w/ 2 levels "A","B": 1 2
    

    为什么 col1 成为num?如何修复它,使其正确成为 Date 现场 df .

    注意:我更喜欢原生的R解决方案,但其他软件包会很有趣

    0 回复  |  直到 6 年前
        1
  •  3
  •   user20650    6 年前

    基于42-的评论 Rather than using list in the "inner" level of construction, use data.frame ,在本例中,可以将内部列表转换为 data.frame ,然后 rbind 一切正常。

    > d = do.call(rbind, lapply(v, as.data.frame))
    > str(d)
    'data.frame':   2 obs. of  2 variables:
     $ col1: Date, format: "2011-01-23" "2012-03-03"
     $ col2: Factor w/ 2 levels "A","B": 1 2
    
        2
  •  3
  •   Sonny    6 年前

    使用 dplyr

    > library(dplyr)
    > df <- bind_rows(v)
    > df
    # A tibble: 2 x 2
      col1       col2 
      <date>     <chr>
    1 2011-01-23 A    
    2 2012-03-03 B