R purrr 累积在嵌套的 tibbles 上
R purrr accumulate over nested tibbles
我需要在嵌套的 tibbles 上累积一个值。
这是我的简化示例:
tab <- data.frame(A = c("A","B","A","B"),
ID = c(1,1,2,2),
V1 = c(20,40,25,30),
V2 = c(0.2,0.8,0.3,0.7)
) %>%
group_by(ID) %>%
nest()
在我的解决方案中,accumulate 函数始终使用 1000 作为初始值,而不是累积的“1000”。
tab %>%
mutate(
G_i = purrr::accumulate(data,
function(G_i,data){
out <- data %>%
group_by(A) %>%
mutate(G_i = G_i+G_i*V2/V1)
sum(out$G_i)
},
.init = 1000)%>%
tail(-1)
)
A tibble: 2 × 3
# Groups: ID [2]
ID data G_i
<dbl> <list> <dbl>
1 1 <tibble [2 × 3]> 2030
2 2 <tibble [2 × 3]> 2035.
所需的输出应交付:
A tibble: 2 × 3
# Groups: ID [2]
ID data G_i
<dbl> <list> <dbl>
1 1 <tibble [2 × 3]> 2030
2 2 <tibble [2 × 3]> 4131.727
感谢您的帮助。
如@MikkoMarttila 所述,您需要做的只是 ungroup
在使用 accumulate
.
之前
library(tidyverse)
tab %>%
ungroup %>%
mutate(
G_i = purrr::accumulate(data,
function(G_i,data){
out <- data %>%
group_by(A) %>%
mutate(G_i = G_i+G_i*V2/V1)
sum(out$G_i)
},
.init = 1000)%>%
tail(-1)
)
输出
ID data G_i
<dbl> <list> <dbl>
1 1 <tibble [2 × 3]> 2030.000
2 2 <tibble [2 × 3]> 4131.727
我需要在嵌套的 tibbles 上累积一个值。
这是我的简化示例:
tab <- data.frame(A = c("A","B","A","B"),
ID = c(1,1,2,2),
V1 = c(20,40,25,30),
V2 = c(0.2,0.8,0.3,0.7)
) %>%
group_by(ID) %>%
nest()
在我的解决方案中,accumulate 函数始终使用 1000 作为初始值,而不是累积的“1000”。
tab %>%
mutate(
G_i = purrr::accumulate(data,
function(G_i,data){
out <- data %>%
group_by(A) %>%
mutate(G_i = G_i+G_i*V2/V1)
sum(out$G_i)
},
.init = 1000)%>%
tail(-1)
)
A tibble: 2 × 3
# Groups: ID [2]
ID data G_i
<dbl> <list> <dbl>
1 1 <tibble [2 × 3]> 2030
2 2 <tibble [2 × 3]> 2035.
所需的输出应交付:
A tibble: 2 × 3
# Groups: ID [2]
ID data G_i
<dbl> <list> <dbl>
1 1 <tibble [2 × 3]> 2030
2 2 <tibble [2 × 3]> 4131.727
感谢您的帮助。
如@MikkoMarttila 所述,您需要做的只是 ungroup
在使用 accumulate
.
library(tidyverse)
tab %>%
ungroup %>%
mutate(
G_i = purrr::accumulate(data,
function(G_i,data){
out <- data %>%
group_by(A) %>%
mutate(G_i = G_i+G_i*V2/V1)
sum(out$G_i)
},
.init = 1000)%>%
tail(-1)
)
输出
ID data G_i
<dbl> <list> <dbl>
1 1 <tibble [2 × 3]> 2030.000
2 2 <tibble [2 × 3]> 4131.727