[R] Local parameter calculation

Tony Plate tplate at blackmesacapital.com
Thu Apr 17 17:41:59 CEST 2003


At Wednesday 01:21 PM 4/16/2003 -0500, Minghua Yao <myao at ou.edu> wrote:
>[...]
>I have 2 vectors X and Y that have a equal length of several thousand. I see
>Y as the function of X. Both of them are random. X is not arrranged in any
>order. Of course, I do plot(X,Y). Now, I want to use a sliding narrow window
>to run over each X, then calculate the variances within that window.
>[...]

Here's an example of how this can be done using general R functions:

 > # Example of randomly ordered data
 > x <- sample(1:10)
 > y <- ifelse(x%%2, x, -x)
 > cbind(x, y)
        x   y
  [1,] 10 -10
  [2,]  3   3
  [3,]  8  -8
  [4,]  1   1
  [5,]  6  -6
  [6,]  7   7
  [7,]  9   9
  [8,]  5   5
  [9,]  2  -2
[10,]  4  -4
 > # Order the data by x
 > x.order <- order(x)
 > x <- x[x.order]
 > y <- y[x.order]
 > cbind(x, y)
        x   y
  [1,]  1   1
  [2,]  2  -2
  [3,]  3   3
  [4,]  4  -4
  [5,]  5   5
  [6,]  6  -6
  [7,]  7   7
  [8,]  8  -8
  [9,]  9   9
[10,] 10 -10
 > # var.window calculates variance on a window of length "len", of z, 
ending at i
 > var.window <- function(i, z, len) var(z[seq(from=max(0,i-len+1),to=i)])
 > sapply(seq(along=x), var.window, z=y, len=3)
  [1]         NA   4.500000   6.333333  13.000000  22.333333  34.333333
  [7]  49.000000  66.333333  86.333333 109.000000
 >

Hope this helps,

Tony Plate



More information about the R-help mailing list