Home > front end >  How can I slide from top to bottom in a dataframe in R with different sliding window using tidyverse
How can I slide from top to bottom in a dataframe in R with different sliding window using tidyverse

Time:10-19

I have a data frame that looks like this :

a b
7 -12
18 -22
29 -32
40 -42
51 -52

I want to slide from top to bottom with:

sliding window 3 :

7 -22 = -15

7 -32 = -25

18 -42 = -24

29 -52 = -23

40 -52 = -12

from this calculations I want R to report me the minimum which is -25.

for sliding window 5 :

7-32 =-25

7-42 = -35

7 -52 = -45

18 -52 =-34

29-52 =-23

and R to report me -45.

How can I do this in R ?

library(tidyverse)
a = c(7,18,29,40,51)
b = c(-12,-22,-32,-42,-52)
w = tibble(a,b);w

CodePudding user response:

For the first step

w = w |> 
  mutate(
    sw3 = lag(a, 1L, default = first(a))    lead(b, 1L, default = last(b)),
    sw5 = lag(a, 2L, default = first(a))    lead(b, 2L, default = last(b))  
  )
#       a     b   sw3   sw5
#   <dbl> <dbl> <dbl> <dbl>
# 1     7   -12   -15   -25
# 2    18   -22   -25   -35
# 3    29   -32   -24   -45
# 4    40   -42   -23   -34
# 5    51   -52   -12   -23

To find the lowest value:

lapply(select(w, sw3, sw5), min)
# $sw3
# [1] -25

# $sw5
# [1] -45

Or

map_dbl(select(w, sw3, sw5), min)
# sw3 sw5 
# -25 -45  

CodePudding user response:

Try

library(dplyr)
df1 %>% 
   mutate(b3 = lead(b, default = last(b)), 
   a3= lag(a, default = first(a)), 
   b_a = b3   a3, 
   b5 = lead(b, n = 2, default = last(b)),
   a5 = lag(a,n = 2, default = first(a)), b_a_5 = b5   a5) %>%
   summarise(out1 = min(b_a), out2 = min(b_a_5))

-output

 out1 out2
1  -25  -45
  • Related