[R] moving a window over a matrix column

David Winsemius dwinsemius at comcast.net
Thu Sep 26 16:08:23 CEST 2013


On Sep 26, 2013, at 8:30 AM, Babak Bastan wrote:

> Greeting
>
> I want to move a window over a column in a Matrix. For example. I  
> have a
> 8X1 Matrix and I want to read the data from 1 until 5, for the  
> second time
> 2 until 6, third time 3 till 7 and... and do something on this  
> values and
> show them in a diagramm:

I tried looking at the code below but could not tell what was failing  
because you did not say what you meant by "did not work". If you got  
an error you should have posted it. I am guessing the "it" you wanted  
plotted were just the values against an index.

The embed function will construct a matrix something like I imagine  
you want, albeit with columns in reverse order:

 > M <- 1:8
 > embed(M, 3)
      [,1] [,2] [,3]
[1,]    3    2    1
[2,]    4    3    2
[3,]    5    4    3
[4,]    6    5    4
[5,]    7    6    5
[6,]    8    7    6

 > layout(c(1:3))
 > for(i in 3:1) plot( embed(M,3)[ , i])

-- 
David.

>
> I wrote this code:
>
> #here I make an nX1 Matrix
>
> df<-matrix(unlist(datalist,use.names=FALSE),ncol=1,byrow=TRUE)#window:
> the length of the window and Step:wenn this value 1 is, then for the
> second time it begins from 2while(n+window<=length(df)){
>  k<-matrix(df[n:n+window-1,1])
>  #plot(k) I want to do something over k and show it in a plot
>  n<-n+step}
>
> but my code doesn't work
>
>   - I can't show a plot inside of for loop
>   - I cant show the value of K inside of for loop
>   - If I show k outside of the loop I can only see one integer value
> and not a matrix
>
> if df:
>
> 12 13 14 15 16 17 18 8 19
>
> then k outside of the loop contain only 18.
>
> Could you please inform me how can I solve my problem?
>
> 	
-- 

David Winsemius, MD
Alameda, CA, USA



More information about the R-help mailing list