Assign range of dates for each unique row in the dataframe.

Providing reprex is always advisable if you want to get input on your problem as fast as possible. There is more info about how to do one here:

Your problem can be solved with a join and unnest from tidyr:

suppressPackageStartupMessages(library(tidyverse))

years <- tibble::tribble(
  ~year, ~dates,
  "2018",  seq(from = as.Date("2018-01-01"), to = as.Date("2018-12-31"), by = "1 day"),
  "2017",  seq(from = as.Date("2017-01-01"), to = as.Date("2017-12-31"), by = "1 day")
)

df <- tibble::tribble(
  ~gpi_year, ~gpi_country, ~gpi_score,
  "2018",      "Iceland",      1.096,
  "2018",      "South Sudan",  3.508,
  "2017",      "Iceland",      2,
  "2017",      "South Sudan",  1
)

options(pillar.sigfig = 4)

df %>%
  dplyr::left_join(years, by = c("gpi_year" = "year")) %>%
  tidyr::unnest(dates)
#> # A tibble: 1,460 x 4
#>    gpi_year gpi_country gpi_score dates     
#>    <chr>    <chr>           <dbl> <date>    
#>  1 2018     Iceland         1.096 2018-01-01
#>  2 2018     Iceland         1.096 2018-01-02
#>  3 2018     Iceland         1.096 2018-01-03
#>  4 2018     Iceland         1.096 2018-01-04
#>  5 2018     Iceland         1.096 2018-01-05
#>  6 2018     Iceland         1.096 2018-01-06
#>  7 2018     Iceland         1.096 2018-01-07
#>  8 2018     Iceland         1.096 2018-01-08
#>  9 2018     Iceland         1.096 2018-01-09
#> 10 2018     Iceland         1.096 2018-01-10
#> # ... with 1,450 more rows

Created on 2018-11-03 by the reprex package (v0.2.1)

5 Likes