How to display real dates in a loop in r

前端 未结 2 1751
渐次进展
渐次进展 2020-12-21 21:58

When I iterate over dates in a loop, R prints out the numeric coding of the dates.

For example:

dates <- as.Date(c(\"1939-06-10\", \"1932-02-22\"         


        
相关标签:
2条回答
  • 2020-12-21 22:46

    When you use dates as seq in a for loop in R, it loses its attributes.

    You can use as.vector to strip attributes and see for yourself (or dput to see under the hood on the full object):

    as.vector(dates)
    # [1] -11163 -13828   3724   6284   6678   3526   8232   7284
    dput(dates)
    # structure(c(-11163, -13828, 3724, 6284, 6678, 3526, 8232, 7284), class = "Date")
    

    In R, Date objects are just numeric vectors with class Date (class is an attribute).

    Hence you're seeing numbers (FWIW, these numbers count days since 1970-01-01).

    To restore the Date attribute, you can use the .Date function:

    for (d in dates) print(.Date(d))
    # [1] "1939-06-10"
    # [1] "1932-02-22"
    # [1] "1980-03-13"
    # [1] "1987-03-17"
    # [1] "1988-04-14"
    # [1] "1979-08-28"
    # [1] "1992-07-16"
    # [1] "1989-12-11"
    

    This is equivalent to as.Date(d, origin = '1970-01-01'), the numeric method for as.Date.

    Funnily enough, *apply functions don't strip attributes:

    invisible(lapply(dates, print))
    # [1] "1939-06-10"
    # [1] "1932-02-22"
    # [1] "1980-03-13"
    # [1] "1987-03-17"
    # [1] "1988-04-14"
    # [1] "1979-08-28"
    # [1] "1992-07-16"
    # [1] "1989-12-11"
    
    0 讨论(0)
  • There are multiple way you can handle this :

    Loop over index of dates :

    for(d in seq_along(dates)){
       print(dates[d])
    }
    
    #[1] "1939-06-10"
    #[1] "1932-02-22"
    #[1] "1980-03-13"
    #[1] "1987-03-17"
    #[1] "1988-04-14"
    #[1] "1979-08-28"
    #[1] "1992-07-16"
    #[1] "1989-12-11"
    

    Or convert date to list and then print directly.

    for(d in as.list(dates)) {
       print(d)
    }
    
    0 讨论(0)
提交回复
热议问题