[R] moving a window over a matrix column

Berend Hasselman bhh at xs4all.nl
Thu Sep 26 16:48:23 CEST 2013


On 26-09-2013, at 15:30, Babak Bastan <babakbsn at gmail.com> 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 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?
> 

It is impossible to give you proper advice since your code has been messed up by posting in HTML.
And you have not given a reproducible example.

Other have already made some suggestions.
I guessing that the expression

 k<-matrix(df[n:n+window-1,1])

is not doing what you expect. You likely want rows n upto and including n+window-1.
If so use () around the part after the : like this

k<-matrix(df[n:(n+window-1),1])

Read the "An Introduction to R" manual especially section 2.3 Generating regular sequences (R-3.0.2)

Berend

> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list