简体   繁体   English

R 多年来平均分布值

[英]R spread value evenly over years

I have a list of values that I want to spread evenly over multiple years in R.我有一个值列表,我想在 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 6.4 2022 2022
A一个 6.4 6.4 2023 2023
A一个 6.4 6.4 2024 2024
A一个 6.4 6.4 2025 2025
A一个 6.4 6.4 2026 2026
A一个 6.4 6.4 2027 2027
B 12.9 12.9 2022 2022
B 12.9 12.9 2023 2023
B 12.9 12.9 2024 2024
B 12.9 12.9 2025 2025
B 12.9 12.9 2026 2026
B 12.9 12.9 2027 2027

Perhaps this helps - divide the 'QTY' by the length of 'years' (+ 1) and use crossing to expand the data也许这有帮助 - 将“数量”除以“年”的length (+ 1)并使用crossing来扩展数据

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM