Search code examples
rwindowtidy

Sliding dataset for x rows R


I have a dataset like the below and would like to create a nested dataframe for the last 20 rows.

x <- rep(1:100, 1)
y <- rnorm(100)
z <- rnorm(100)*2

data.frame(x,y,z)

For example, where x = 100 it would include the records for rows where x = 81:100, x = 99 would include 80:99 and so on. If there are not 20 rows before it would only include the number of rows before like 15 would include 1:15.

The ideal output would be nested so functions could be applied to all dataframes


Solution

  • If I've correctly understood, this function should fit:

    #library
    library(tidyverse)
    
    #data
    x <- rep(1:100, 1)
    y <- rnorm(100)
    z <- rnorm(100)*2
    
    dataf <- data.frame(x,y,z)
    
    #working function
    getDf <- function(df, n) {
    
      if (n >= 19) {
    
        return(df %>% slice((n-19):n))  
    
      } else {
    
        return(df %>% slice(1:n))
    
      }
    
    }
    
    #examples
    getDf(dataf,100)
    
    getDf(dataf,99)
    
    getDf(dataf,15)