Hi I'm using slide_index() to capture values in a time window for every row in a dataframe. However, for every row I'll also be comparing the value of the current row against the captured values for that row's window. Part of the logic I'm using requires the current row's value to be excluded from the captured values during each row's iteration.
I think there are 2 ways to get around this: 1. I can pass in the current row's value directly into a custom function logic I'm using in slide_index(.f), or 2. I can exclude the current row's value from the values captured for the row's sliding window. I couldn't find any resources for the first route, so I'm wondering if the second route is feasible either.
library(slider)
x <- c(rep(1:16))
i <- as.Date("2019-08-15") + c(0:15)
slide_index(x, i, ~.x, .before = 2, .after = 2)
For example, going off the reproducible code above the output from slide_index() at the second iteration when x = 2 would be: [1] 1 2 3 4. But I'd want the output to either return only [1] 1 3 4, or get a way to read in the current x value into the custom function I'd pass into slide_index(.f)
Edit: Second example with group_by
library(slider)
library(tidyverse)
x <- c(10, 12, 12, 14, 11, 22, 25, 25, 33, 31, 34, 36, 23, 24, 29, 13)
y <- c(10, 12, 12, 14, 11, 22, 25, 25, 33, 31, 34, 36, 23, 24, 29, 13)
group <- c(rep(as.character('A'), 5), rep(as.character('B'), 4), rep(as.character('C'), 1), rep(as.character('D'), 6))
df <- data.frame(group, x, y, dates) %>%
mutate(group = as.factor(group))
df %>%
group_by(group) %>%
do(mutate(., result = slide_index(.x = ., .i = .$dates, ~median(.$y), .before = 2, .after = 2)
%>% unlist()
)
)
I also tried this but it didn't work
df %>%
group_by(group) %>%
do(mutate(., result = max(map2(slide_index(.x = seq_along(.), .i = .$dates, .f = ~.$y, .before = 2, .after = 2), seq_along(.), ~.[setdiff(.x, .y)] )
)
)
)