【问题标题】:Summing up Certain Sequences of a Dataframe in R在 R 中总结数据帧的某些序列
【发布时间】:2021-03-31 09:29:38
【问题描述】:

我有几个按年龄组划分的不同地区每日费率的数据框:

Date         0-14 Rate     15-29 Rate  30-44 Rate   45-64 Rate 65-79 Rate  80+ Rate   
2020-23-12     0              33.54      45.68       88.88        96.13      41.28 
2020-24-12     0              25.14      35.28       66.14        90.28      38.41

从星期三 (2020-23-12) 开始,我有从那时起的最新数据。

我想获得每周三到周二的费率行总和。

应该有一种明智的方法来组合聚合、seq 和 rowsum 函数来使用几行代码来做到这一点。否则,我将使用太长的方法来做到这一点。

【问题讨论】:

  • 你想要的输出格式是什么?

标签: r dplyr tidyverse


【解决方案1】:

我创建了一些最少的数据,三周内包含一些任意列和数字(没有遗漏)。您可以使用tidyverse 语言对列求和、每周创建组并按周对行求和:

# Minimal Data 
MWE <- data.frame(date = c(outer(as.Date("12/23/20", "%m/%d/%y"), 0:20, `+`)),
                  column1 = runif(21,0,1),
                  column2 = runif(21,0,1))

library(tidyverse)

MWE %>%
  # Calculate Row Sum Everywhere
  mutate(sum = rowSums(across(where(is.numeric)))) %>%
  # Create Week Groups
  group_by(week = ceiling(row_number()/7)) %>%
  # Sum Over All RowSums per Group 
  summarise(rowSums_by_week = sum(sum))


# Groups:   week [3]
   date       column1 column2   sum  week
   <date>       <dbl>   <dbl> <dbl> <dbl>
 1 2020-12-23   0.449  0.759  1.21      1
 2 2020-12-24   0.423  0.0956 0.519     1
 3 2020-12-25   0.974  0.592  1.57      1
 4 2020-12-26   0.798  0.250  1.05      1
 5 2020-12-27   0.870  0.487  1.36      1
 6 2020-12-28   0.952  0.345  1.30      1
 7 2020-12-29   0.349  0.817  1.17      1
 8 2020-12-30   0.227  0.727  0.954     2
 9 2020-12-31   0.292  0.209  0.501     2
10 2021-01-01   0.678  0.276  0.954     2
# ... with 11 more rows

# A tibble: 3 x 2
   week rowSums_by_week
  <dbl>           <dbl>
1     1            8.16
2     2            6.02
3     3            6.82

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多