0

I have the dataframe below

Año inicio Año final Resultado
2000 2001 4
2002 2005 2

and I would like to transform it into

Año inicio Año final Año Resultado
2000 2001 2000 4
2000 2001 2001 4
2002 2005 2002 2
2002 2005 2003 2
2002 2005 2004 2
2002 2005 2005 2

using R.

May u help me?

2 Answers2

1

One option is to create a sequence for each row, stored as a list, and then unnest it:

library(dplyr)
library(tidyr)

tribble(
  ~"Año inicio", ~"Año final",  ~"Resultado",
  2000, 2001,   4,
  2002, 2005,   2,
) %>% 
  rowwise() %>% 
  mutate(`Año` = list(seq(`Año inicio`, `Año final`)), .before = "Resultado") %>% 
  ungroup() %>% 
  unnest(`Año`)
#> # A tibble: 6 × 4
#>   `Año inicio` `Año final`   Año Resultado
#>          <dbl>       <dbl> <int>     <dbl>
#> 1         2000        2001  2000         4
#> 2         2000        2001  2001         4
#> 3         2002        2005  2002         2
#> 4         2002        2005  2003         2
#> 5         2002        2005  2004         2
#> 6         2002        2005  2005         2

Created on 2023-05-09 with reprex v2.0.2

margusl
  • 7,804
  • 2
  • 16
  • 20
0

We can do it with uncount and some tweaking:

library(tidyr)
library(dplyr)


df %>%
  uncount(Año_final - Año_inicio + 1) %>%
  mutate(Año = seq(first(Año_inicio), last(Año_final)))

    Año_inicio Año_final Resultado  Año
1       2000      2001         4 2000
2       2000      2001         4 2001
3       2002      2005         2 2002
4       2002      2005         2 2003
5       2002      2005         2 2004
6       2002      2005         2 2005

data:

df <- structure(list(Año_inicio = c(2000, 2002), Año_final = c(2001, 
2005), Resultado = c(4, 2)), class = "data.frame", row.names = c(NA, 
-2L))
TarJae
  • 72,363
  • 6
  • 19
  • 66