Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R spread value evenly over years

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading