How about considering 'embed':
> d
Date Close
1 2011-01-28 56.42
2 2011-01-27 57.37
3 2011-01-26 56.48
4 2011-01-25 56.39
5 2011-01-24 55.74
6 2011-01-21 55.46
> x <- embed(d$Close, 4)
> x
[,1] [,2] [,3] [,4]
[1,] 56.39 56.48 57.37 56.42
[2,] 55.74 56.39 56.48 57.37
[3,] 55.46 55.
On Sun, Jan 30, 2011 at 1:39 PM, eric wrote:
>
> I'd like to use vectorization to take a 4 point moving window on standard
> deviation on the close column and create another variable (st.dev) in the
> dataframe. Here's the dataframe
>
>
> head(xyz)
> Date Close
> 1 2011-01-28 56.42
> 2 2011
I believe there are two reasons why your code doesn't work
1. You should replace
sd(Close[i]:Close[(i-3)])
with
sd(Close[(i-3):i]).
This will ensure you select the appropriate obsevations to feed in the sd
function.
2. Per Ray's point above, you need to output the calculated value of sd fo
On Mon, 31 Jan 2011, eric wrote:
> I'd rather do this without getting into zoo objects at the moment. OK, how
> about with a simple loop ? Why doesn't this work ?
>
> attach(xyz)
> j <- for(i in 4: length(Close)) sd(Close[i]:Close[(i-3)])
To answer your question, it is because the value returned f
how about ...
j=NULL
for(i in 4: length(xyz$Close)) {
j[i] = sd(xyz$Close[i-3:i])
}
print(j)
--
View this message in context:
http://r.789695.n4.nabble.com/How-to-do-a-moving-window-on-standard-deviation-tp3247566p3247634.html
Sent from the R help mailing list archive at Nabble.com.
_
I'd rather do this without getting into zoo objects at the moment. OK, how
about with a simple loop ? Why doesn't this work ?
attach(xyz)
j <- for(i in 4: length(Close)) sd(Close[i]:Close[(i-3)])
--
View this message in context:
http://r.789695.n4.nabble.com/How-to-do-a-moving-window-on-standar
One way is to convert your data into a zoo object and use the rollapply
function
# Your data
lines = "Date Close
2011-01-28 56.42
2011-01-27 57.37
2011-01-26 56.48
2011-01-25 56.39
2011-01-24 55.74
2011-01-21 55.46"
d = read.table(textConnection(lines), header = TRUE)
# create zoo object
d.z=z
I'd like to use vectorization to take a 4 point moving window on standard
deviation on the close column and create another variable (st.dev) in the
dataframe. Here's the dataframe
head(xyz)
Date Close
1 2011-01-28 56.42
2 2011-01-27 57.37
3 2011-01-26 56.48
4 2011-01-25 56.39
5 2011-01-2
8 matches
Mail list logo