How should I code in R if I make the left structure to the right one?
Asked
Active
Viewed 46 times
0
-
2Welcome to Stack Overflow. What have you tried so far? Can you please post your input and output in a textual form (e.g. cut-and-pasted text in a code format) rather than as an image? Images are un-searchable and inaccessible to people using screen readers ... – Ben Bolker Mar 11 '22 at 23:17
-
2Welcome to the community! Check it out: [making R reproducible questions](https://stackoverflow.com/q/5963269). – Kat Mar 12 '22 at 00:25
2 Answers
1
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

Ben
- 28,684
- 5
- 23
- 45
1
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

Ronak Shah
- 377,200
- 20
- 156
- 213