I have a list of values that I want to spread evenly over multiple years in R. I think I'm missing something right in front of me.
I have:
#Create dataframe
df <- data.frame(product=rep(c('A','B')),
QTY = c('45', '90'))
#Check
df
# List Years
years <- c(2022:2027)
I would like to spread the values of each product evenly over the years listed ending with something like
Product | QTY | Year |
---|---|---|
A | 6.4 | 2022 |
A | 6.4 | 2023 |
A | 6.4 | 2024 |
A | 6.4 | 2025 |
A | 6.4 | 2026 |
A | 6.4 | 2027 |
B | 12.9 | 2022 |
B | 12.9 | 2023 |
B | 12.9 | 2024 |
B | 12.9 | 2025 |
B | 12.9 | 2026 |
B | 12.9 | 2027 |
CodePudding user response:
Perhaps this helps - divide the 'QTY' by the length
of 'years' ( 1) and use crossing
to expand the data
library(dplyr)
library(tidyr)
df %>%
mutate(QTY = as.numeric(QTY)/(length(years) 1)) %>%
crossing(Year = years)
-output
# A tibble: 12 × 3
product QTY Year
<chr> <dbl> <int>
1 A 6.43 2022
2 A 6.43 2023
3 A 6.43 2024
4 A 6.43 2025
5 A 6.43 2026
6 A 6.43 2027
7 B 12.9 2022
8 B 12.9 2023
9 B 12.9 2024
10 B 12.9 2025
11 B 12.9 2026
12 B 12.9 2027