dplyr - How to convert week and year columns to a date column with lubridate in R -


i have been following along hadley wickham's r data science book. has lot of advice on using lubridate, lot of functions assume have year, month, , day. how convert date format when have year , week using lubridate?

data.frame(     year = c(2015, 2015, 2016, 2016, 2016, 2016, 2016),     week = c(1, 20, 35, 49, 8, 4, 53)   )  #year   week #2015    1 #2015    20 #2016   35   #2016   49   #2016   8    #2016   4    #2016   53 

you can weeks() function in lubridate, if want. have first set baseline date object. did here using str_c stringr.

library(dplyr) library(stringr)  my_dates <- tribble(     ~year,   ~week,     2015,    1,     2015,    20,     2016,    35,       2016,    49,       2016,    8,       2016,    4,        2016,    53 )  my_dates %>%     mutate(beginning = ymd(str_c(year, "-01-01")),            final_date = beginning + weeks(week)) #> # tibble: 7 x 4 #>    year  week  beginning final_date #>   <dbl> <dbl>     <date>     <date> #> 1  2015     1 2015-01-01 2015-01-08 #> 2  2015    20 2015-01-01 2015-05-21 #> 3  2016    35 2016-01-01 2016-09-02 #> 4  2016    49 2016-01-01 2016-12-09 #> 5  2016     8 2016-01-01 2016-02-26 #> 6  2016     4 2016-01-01 2016-01-29 #> 7  2016    53 2016-01-01 2017-01-06 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -