Re: [R] year and week to date - before 1/1 and after 12/31

2018-10-18 Thread peter salzman
thanks Jeff and Gabor, appreciate you spending time on this, you both use similar ideas - add/subtract days/weeks from a day that exists combining all i learned i would go with something like this: ## step 1) find 1st sunday of year Y d11 <- as.Date( sprintf( "%04d 1 1"

Re: [R] year and week to date - before 1/1 and after 12/31

2018-10-18 Thread Gabor Grothendieck
Replace the week in the date with week 2, say -- a week in which nothing will go wrong and then add or subtract the appropriate number of weeks. d <- c('2016 00 Sun', '2017 53 Sun', '2017 53 Mon') # test data as.Date(sub(" .. ", "02", d), "%Y %U %a") + 7 * (as.numeric(sub(" (..)

Re: [R] year and week to date - before 1/1 and after 12/31

2018-10-17 Thread Jeff Newmiller
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"

Re: [R] year and week to date - before 1/1 and after 12/31

2018-10-16 Thread peter salzman
hi, thanks for replying, it has taken some time to understand i have year+week and i need to find the 1st day and the last day of that week i can decide when week starts for example these 3 examples: df <- data.frame(id = 1:3, year = c(2018, 2018, 2018), week=c(0,1,52)) ## now run for all 3

Re: [R] year and week to date - before 1/1 and after 12/31

2018-10-16 Thread Jeff Newmiller
Er, my mistake, you are using %U not %W... but now I am really confused, because the first Sunday is trivial with %U/%u. Can you clarify what your actual upstream input is? Is it an invalid date string as you say below, or is it year number? On October 16, 2018 10:22:10 AM PDT, Jeff Newmiller

Re: [R] year and week to date - before 1/1 and after 12/31

2018-10-16 Thread Jeff Newmiller
If the date in your character representation does not exist then there is no requirement for a POSIX function to give any reliable answer... including NA. Using 00 as the week number won't always work. The first week/weekday combination that is guaranteed to exist by POSIX is 1/1 (first

Re: [R] year and week to date - before 1/1 and after 12/31

2018-10-16 Thread peter salzman
it is simpler than i thought first day of given week is the last day minus 6days in other words: d1 = as.Date('2018 00 Sat',format="%Y %U %a") - 6 d2 = as.Date('2018 00 Sun',format="%Y %U %a") are the same as long both are not NA therefore to get the one that is not NA one can do max(

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

2018-10-16 Thread peter salzman
hi, to turn year and week into the date one can do the following: as.Date('2018 05 Sun', "%Y %W %a") however, when we want the Sunday (1st day of week) of the 1st week of 2018 we get NA because 1/1/2018 was on Monday as.Date('2018 00 Mon',format="%Y %U %a") ## 2018-01-01 as.Date('2018 00