Search code examples
rsubset

Unnest/Unlist moving window results in R


I have a dataframe that has two columns, x and y (both populated with numbers). I am trying to look at a moving window within the data, and I've done it like this (source):

# Extract just x and y from the original data frame
df <- dat_fin %>% select(x, y)

# Moving window creation
nr <- nrow(df)
windowSize <- 10
windfs <- lapply(seq_len(nr - windowSize + 1), function(i) df[i:(i + windowSize - 1), ])

This lapply creates a list of tibbles that are each 10 (x, y) pairs. At this point, I am trying to compute a single quantity using each of the sets of 10 pairs; my current (not working) code looks like this:

library(shotGroups)
for (f in 1:length(windfs)) {
  tsceps[f] = getCEP(windfs[f], accuracy = TRUE)
}

When I run this, I get the error:

Error in getCEP.default(windfs, accuracy = TRUE) : xy must be numeric

My goal is that the variable that I've called tsceps should be a 1 x length(windfs) data frame, each value in which comes from the getCEP calculation for each of the windowed subsets.

I've tried various things with unnest and unlist, all of which were unsuccessful.

What am I missing?


Solution

  • Working code:

    df <- dat_fin %>% select(x, y)
    
    nr <- nrow(df)
    windowSize <- 10
    windfs <- lapply(seq_len(nr - windowSize + 1), function(i) df[i:(i + windowSize - 1), ])
    
    tsceps <- vector(mode = "numeric", length = length(windfs))
    
    library(shotGroups)
    
    for (j in 1:length(windfs)) {
      tsceps[j] <- getCEP(windfs[[j]], type = "CorrNormal", CEPlevel = 0.50, accuracy = TRUE)
    }
    
    ults <- unlist(tsceps)
    
    ults_cep <- vector(mode = "numeric", length = length(ults))
    
    for (k in 1:length(ults)) {
      ults_cep[k] <- ults[[k]]
    }
    

    To get this working with multiple type arguments to getCEP, just use additional code blocks for each type required.