簡體   English   中英

在分組的 dplyr 數據框中迭代應用函數以在 R 中創建列

[英]Applying a function iteratively in a grouped dplyr dataframe to create a column in R

假設我得到以下輸入數據框:

ID  Date
1   20th May, 2020
1   21st May, 2020
1   28th May, 2020
1   29th May, 2020
2   20th May, 2020
2   1st June, 2020

我想生成以下數據框:

ID  Date            Delta
1   20th May, 2020      0
1   21st May, 2020      1
1   28th May, 2020      7
1   29th May, 2020      1
2   20th May, 2020      0
2   1st June, 2020     12

這個想法在哪里,首先我按id分組。 然后在我當前的id 我迭代這些天並將當前日期與前一個日期相減,第一個日期除外,它只是它本身。

我一直在使用 dplyr,但我不確定如何為團體實現這一目標以及如何迭代地做到這一點

我的目標是過濾增量並保留 0 和任何大於 7 的值,但它必須遵循特定id的“前一天”邏輯。

library(dplyr)
dat %>%
  mutate(Date = as.Date(gsub("[a-z]{2} ", " ", Date), format = "%d %b, %Y")) %>%
  group_by(ID) %>%
  mutate(Delta = c(0, diff(Date))) %>%
  ungroup()
# # A tibble: 6 x 3
#      ID Date       Delta
#   <dbl> <date>     <dbl>
# 1     1 2020-05-20     0
# 2     1 2020-05-21     1
# 3     1 2020-05-28     7
# 4     1 2020-05-29     1
# 5     2 2020-05-20     0
# 6     2 2020-06-01    12

腳步:

  1. 從數字中刪除序數,這樣我們就可以
  2. 將它們轉換為正確的Date類對象,然后
  3. diff他們內ID組。

數據

dat <- structure(list(ID = c(1, 1, 1, 1, 2, 2), Date = c("  20th May, 2020", "  21st May, 2020", "  28th May, 2020", "  29th May, 2020", "  20th May, 2020", "  1st June, 2020")), class = "data.frame", row.names = c(NA, -6L))

與@r2evans 類似的邏輯,但具有不同的功能。

library(dplyr)
library(lubridate)

df %>%
  mutate(Date = dmy(Date)) %>%
  group_by(ID) %>%
  mutate(Delta = as.integer(Date - lag(Date, default = first(Date)))) %>%
  ungroup

#     ID Date       Delta
#  <int> <date>     <int>
#1     1 2020-05-20     0
#2     1 2020-05-21     1
#3     1 2020-05-28     7
#4     1 2020-05-29     1
#5     2 2020-05-20     0
#6     2 2020-06-01    12

數據

df <- structure(list(ID = c(1L, 1L, 1L, 1L, 2L, 2L), Date = c("20th May, 2020", 
"21st May, 2020", "28th May, 2020", "29th May, 2020", "20th May, 2020", 
"1st June, 2020")), class = "data.frame", row.names = c(NA, -6L))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM