-1

I have a problem that is very similar to this:

R transform data frame with start and end year into time series however, none of the solutions have worked for me.

This the original df:

df <- data.frame(country = c("Albania", "Albania", "Albania"), leader = c("Sali Berisha", "Sali Berisha", "Sali Berisha"), term = c(2, 2, 2), yearbegin = c(2009,2009, 2009), yearend = c(2013, 2013, 2013))

And it currently looks like this:

#>    country    leader         term  yearbegin  yearend
#> 1   Albania    Sali Berisha    2    2009       2013
#> 2   Albania    Sali Berisha    2    2009       2013
#> 3   Albania    Sali Berisha    2    2009       2013

And I'm trying to get it to look like this:

#> 1    Albania  Sali Berisha   2      2009
#> 2    Albania  Sali Berisha   2      2010
#> 3    Albania  Sali Berisha   2      2011
#> 4    Albania  Sali Berisha   2      2012
#> 5    Albania  Sali Berisha   2      2013

When using this code:

library(tidyverse)
 gpd_df<- gpd_df %>% 
  mutate(year = map2(yearbegin, yearend, `:`)) %>% 
  select(-yearbegin, -yearend) %>% 
  unnest```

I get a column that looks like this:

```year
2009:2013
2009:2013
2009:2013

Many thanks in advance for your help!!

trying to transform date into time-series form year begin/year end. Have just found errors :')

hazel
  • 3
  • 2

1 Answers1

0

Use distinct first:

library(dplyr)
library(tidyr)
gpd_df %>% 
  distinct() %>% 
  mutate(year = map2(yearbegin, yearend, `:`), .keep = "unused") %>% 
  unnest_longer(year)

  country leader        term  year
1 Albania Sali Berisha     2  2009
2 Albania Sali Berisha     2  2010
3 Albania Sali Berisha     2  2011
4 Albania Sali Berisha     2  2012
5 Albania Sali Berisha     2  2013
Maël
  • 45,206
  • 3
  • 29
  • 67
  • 1
    thank you Mael! I seem to still be getting the output with the year variable as '2009:2013' but maybe there's an issue with the rest of the df - i'll keep trying :) – hazel Feb 17 '23 at 11:11