Dear all, I am a newbie in R. I encounter a problem as follows. 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. Anyone knows easy way in R to do this? Reply is appreciated. -MY
I suspect running() or wapply() in the `gregmisc' package would suit your need. HTH, andy> -----Original Message----- > From: Minghua Yao [mailto:myao at ou.edu] > Sent: Wednesday, April 16, 2003 2:21 PM > To: r-help at stat.math.ethz.ch > Subject: [R] Local parameter calculation > > > Dear all, > > I am a newbie in R. I encounter a problem as follows. > > 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. > > Anyone knows easy way in R to do this? Reply is appreciated. > > -MY > > ______________________________________________ > R-help at stat.math.ethz.ch mailing list > https://www.stat.math.ethz.ch/mailman/listinfo/r-help >
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