gpt4 book ai didi

R 累积 bind.rows

转载 作者:行者123 更新时间:2023-12-01 13:17:45 26 4
gpt4 key购买 nike

我想找到累积的 bind.rows。这是我想要实现的小例子。我将使用 dslabs 包中的 gapminder 数据集进行演示。

library(tidyverse)
library(dslabs)

gapminder %>%
group_by(year) %>%
nest() %>%
head(5)

A tibble: 5 x 2
year data
<int> <list>
1 1960 <tibble [185 x 8]>
2 1961 <tibble [185 x 8]>
3 1962 <tibble [185 x 8]>
4 1963 <tibble [185 x 8]>
5 1964 <tibble [185 x 8]>

我想创建一个列,它将数据列中的早期观察结果绑定(bind)在一起。因此,例如,第 1 行只有 1960 年的数据,第 2 行有 1960 + 1961 年的数据,第 3 行有 1960 + 1961 + 1963 年的数据......最终结果应该是这样的。

# A tibble: 5 x 3
year data cumulative_data
<int> <list> <list>
1 1960 <tibble [185 x 8]> <tibble [185 x 8]>
2 1961 <tibble [185 x 8]> <tibble [370 x 8]>
3 1962 <tibble [185 x 8]> <tibble [555 x 8]>
4 1963 <tibble [185 x 8]> <tibble [740 x 8]>
5 1964 <tibble [185 x 8]> <tibble [925 x 8]>

最佳答案

使用 accumulate = TRUE 选项的

Reduce 允许实现这一点:

gapminder %>%
group_by(year) %>%
nest() %>%
head(5) %>%
mutate(cumulative_data = Reduce(rbind, data, accumulate = TRUE))
# A tibble: 5 x 3
# year data cumulative_data
# <int> <list> <list>
# 1 1960 <tibble [185 × 8]> <tibble [185 × 8]>
# 2 1961 <tibble [185 × 8]> <tibble [370 × 8]>
# 3 1962 <tibble [185 × 8]> <tibble [555 × 8]>
# 4 1963 <tibble [185 × 8]> <tibble [740 × 8]>
# 5 1964 <tibble [185 × 8]> <tibble [925 × 8]>

关于R 累积 bind.rows,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53130421/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com