Skip to content
Prev 377020 / 398502 Next

year and week to date - before 1/1 and after 12/31

You cannot obtain a predictable result by sending invalid time 
representation data to strptime... you have to work with valid time 
representations.
See sample approach below:

############################
weekEnds <- function( DF ) {
    d1_1 <- as.Date( sprintf( "%04d 1 1"
                            , DF[[ "Y" ]]
                            )
                   , format = "%Y %U %u"
                   )
    d52_7 <- as.Date( sprintf( "%04d 52 7"
                             , DF[[ "Y" ]]
                             )
                    , format = "%Y %U %u"
                    )
    week <- as.difftime( 7, units = "days" )
    day <- as.difftime( 1, units = "days" )
    d <- as.Date( sprintf( "%04d %d 1"
                         , DF[[ "Y" ]]
                         , DF[[ "wn" ]]
                         )
                , format = "%Y %U %u"
                )
    before <- 0 == DF[[ "wn" ]]
    after <- 53 == DF[[ "wn" ]]
    d[ before ] <- d1_1[ before ] - week
    d[ after ] <- d52_7[ after ] + day
    DF[[ "weekBegin" ]] <- d
    DF[[ "weekEnd" ]] <- d + week
    DF
}

tst <- expand.grid( Y = 2000:2028
                   , wn = c( 0, 1, 53 )
                   )

result <- weekEnds( tst )
set.seed( 42 )
result[ sample( nrow( result ), 5 ), ]
#>       Y wn  weekBegin    weekEnd
#> 80 2021 53 2021-12-27 2022-01-03
#> 81 2022 53 2022-12-26 2023-01-02
#> 25 2024  0 2024-01-01 2024-01-08
#> 70 2011 53 2011-12-26 2012-01-02
#> 54 2024  1 2024-01-08 2024-01-15
sum( is.na( result$weekBegin ) )
#> [1] 0
############################
On Tue, 16 Oct 2018, peter salzman wrote:

            
---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                       Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
---------------------------------------------------------------------------