【问题标题】:sum numeric variable six months ago六个月前的总和数值变量
【发布时间】:2022-01-08 06:13:25
【问题描述】:

我有一个包含日期和数字变量的数据库。我每个 id 也有多行。它看起来像这样:

ID date x
1 2019-01-01 3
1 2018-12-01 4
1 2017-11-01 1
1 2017-10-01 2
1 2017-09-01 2
1 2017-08-01 2

我需要从 date 到 6 个月前总结 x,所以我尝试了这个

library(lubridate)
    mutate(semester= semester(fecha_inicio,with_year = TRUE)) %>%
  group_by(ID,semester) %>%
  mutate(sum_semester = sum(x, na.rm = TRUE))

但这不是我需要的,因为2019-01-01 有 3 个而不是 14 个。

请帮忙。

【问题讨论】:

  • 你在向mutate发送什么消息?是数据,是的,但代码中缺少它。
  • 只需使用summarise 而不是mutate

标签: r date lubridate


【解决方案1】:

我在这里找到了答案Cumulative sum from a month ago until the current day for all the rows 修改代码:

library(tidyverse)
library(lubridate)
data <- data %>%
  group_by(ID) %>%
  mutate(sum_6m = map_dbl(1:n(), ~ sum(x[(date>= (date[.] - months(5))) &
                                                   (date<= date[.])], na.rm = TRUE)))

【讨论】:

  • 我觉得你的代码不对。
【解决方案2】:

使用经典的方式聚合数据集 x ~ id 通过sumnormal data.frame filter 之类的函数,它可能是以下代码。

代码

library(lubridate)

# Define your data
data <- 
"id date x
1 2019-01-01 3
1 2018-12-01 4
1 2017-11-01 1
1 2017-10-01 2
1 2018-02-12 2
1 2017-09-01 2
"
# Read the table 
tab <- read.csv(text=data, header = T, sep=' ')

# Find the youngest date
top.date <- as.Date(max(tab$date))

# Calculate the threshold (before and after point) of 6 month
thresh   <- top.date) %m-% months(6)

# Calculate the sums over the ID's after the point date
after.thresh  <- aggregate(x ~ id, 
                           data = tab[as.Date(tab$date) >= thresh,], 
                           FUN  = sum)

# Calculate the sums over the ID's before the point date
before.thresh <- aggregate(x ~ id, 
                           data = tab[as.Date(tab$date) < thresh,], 
                           FUN=sum)

# Print the dates 
cat("TOP.DATE.IS:", format_ISO8601(top.date),
    " THRESH.DATE.IS:", format_ISO8601(thresh),"\n")

# Print the sums 
cat("SUM.BEFORE.THRESH:", after.thresh$x, 
    "SUM.AFTER.THRESH:", before.thresh$x,"\n")

结果

TOP.DATE.IS: 2019-01-01  THRESH.DATE.IS: 2018-07-01 
SUM.BEFORE.THRESH: 7 SUM.AFTER.THRESH: 7

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    • 2018-07-05
    • 2013-05-22
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    相关资源
    最近更新 更多