Home > Software design >  Transform the data structure
Transform the data structure

Time:03-12

How should I code in R if I make the left structure to the right one?

enter image description here

enter image description here

CodePudding user response:

If you are starting with a data.frame like this:

df <- data.frame(
  wave = c("2019-2021", "2022-2024"),
  a = 3:4,
  b = 5:6
)

df
       wave a b
1 2019-2021 3 5
2 2022-2024 4 6

Then, with tidyverse you can extract the numeric years from the wave column and create a sequence of years from those two years.

library(tidyverse)

df %>%
  mutate(years = map(
    str_extract_all(wave, "\\d{4}"),
    ~as.numeric(.x[1]):as.numeric(.x[2])
  )) %>% 
  unnest_longer(years)

Output

  wave          a     b years
  <chr>     <int> <int> <int>
1 2019-2021     3     5  2019
2 2019-2021     3     5  2020
3 2019-2021     3     5  2021
4 2022-2024     4     6  2022
5 2022-2024     4     6  2023
6 2022-2024     4     6  2024

CodePudding user response:

Here's another tidyverse option -

library(tidyverse)

df %>%
  separate(wave, c('start', 'end'), sep = '-', convert = TRUE,remove = FALSE) %>%
  mutate(year = map2(start, end, seq)) %>%
  unnest(year) %>%
  select(wave, year, a, b)

#  wave       year     a     b
#  <chr>     <int> <int> <int>
#1 2019-2021  2019     3     5
#2 2019-2021  2020     3     5
#3 2019-2021  2021     3     5
#4 2022-2024  2022     4     6
#5 2022-2024  2023     4     6
#6 2022-2024  2024     4     6
  •  Tags:  
  • r
  • Related