【问题标题】:R cumulative bind.rowsR 累积绑定行
【发布时间】:2018-11-04 03:37:17
【问题描述】:

我想累积地找到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]>

我想创建列,它将数据列中的早期观察结果绑定在一起。例如,第 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]>

【问题讨论】:

    标签: r bind


    【解决方案1】:

    Reduceaccumulate = TRUE 选项可以实现:

    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]>
    

    【讨论】:

      【解决方案2】:

      tidyverse中,我们也可以从purrr使用accumulate

      library(tidyverse)
      library(dslabs)
      gapminder %>%
         group_by(year) %>% 
         nest() %>% 
         head(5) %>%
         mutate(cumulative_data = accumulate(data, bind_rows)) 
      # 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]>
      

      【讨论】:

        猜你喜欢
        • 2018-11-09
        • 1970-01-01
        • 2014-06-21
        • 2014-09-29
        • 2020-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多