資料:
df <- data.frame(year = c(2018, 2019, 2020, 2021),
growth = c(0.05, 0.1, 0.08, 0.06),
size = c(100, NA, NA, NA))
year growth size
1 2018 0.05 100
2 2019 0.10 NA
3 2020 0.08 NA
4 2021 0.06 NA
我有年度規模2018和隨后幾年的增長率。我的目標是將隨后每一年的大小計算為size[i] = size[i-1] * (1 growth[i]). 我可以用 for 回圈做到這一點:
for (i in (2:nrow(df))) {
df$size[i] <- df$size[i-1] * (1 df$growth[i])
}
year growth size
1 2018 0.05 100.000
2 2019 0.10 110.000
3 2020 0.08 118.800
4 2021 0.06 125.928
但是我找不到dplyr做同樣事情的方法,mutate例如。希望聽到你的想法。謝謝!
uj5u.com熱心網友回復:
由于 的第一個值size實際上是列其余部分的乘法常數,因此我們可以僅使用的cumprod(累積乘積)1 growth來獲得乘以size[1]填充size列其余部分的因子。
稍微復雜一點是您的演算法必須忽略 的第一個值growth。我們可以通過使用組合避開這個lead和lag。
因此,以下無需使用回圈即可作業。
library(dplyr)
mutate(df, size = lag(size[1] * cumprod(lead(growth 1)), default = size[1]))
#> year growth size
#> 1 2018 0.05 100.000
#> 2 2019 0.10 110.000
#> 3 2020 0.08 118.800
#> 4 2021 0.06 125.928
uj5u.com熱心網友回復:
一個解決方案purrr::reduce:
library(tidyverse)
df <- data.frame(year = c(2018, 2019, 2020, 2021),
growth = c(0.05, 0.1, 0.08, 0.06),
size = c(100, NA, NA, NA))
reduce(2:nrow(df), function(x,y)
{x$size[y] <- x$size[y-1]*(1 x$growth[y]); x}, .init=df)
#> year growth size
#> 1 2018 0.05 100.000
#> 2 2019 0.10 110.000
#> 3 2020 0.08 118.800
#> 4 2021 0.06 125.928
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/340139.html
