I'm trying to duplicate something in Excel, where it is easy to reference the previous row in formula. Have been stuck on this for ages trying to achieve the same result in R. I've managed to do it with a loop but it takes ages on a large data set. 

What I want to do is create a new variable in a matrix that will refer to it's previous value if the ifelse statements aren't met. 

> f <-read.csv("testdata.csv",header=FALSE, nrows=30 ) 
> f <-subset(f,select=c(V1,V2,V3,V4,V5)) 
> names(f)<-c("date","open","high","low","close") 
> f$test <-0 
> f$test <- ifelse(f$close<Lag(f$low),1,ifelse(f$close>Lag(f$high),-1,Lag(f$test))) 
> f 
date open high low close Lag.1 
1 19830216 1737 1742 1735 1739 NA 
2 19830217 1738 1745 1738 1742 0 
3 19830218 1740 1744 1738 1739 0 
4 19830221 1730 1730 1721 1721 1 
5 19830222 1715 1720 1714 1720 1 
6 19830223 1711 1712 1702 1709 1 
7 19830224 1708 1716 1708 1716 -1 
8 19830225 1718 1726 1718 1718 -1 
9 19830228 1712 1713 1701 1704 1 
10 19830301 1690 1694 1683 1689 1 
11 19830302 1698 1713 1698 1708 -1 
12 19830303 1714 1721 1711 1714 -1 
13 19830304 1717 1725 1714 1721 0 
14 19830307 1715 1738 1715 1735 -1 
15 19830308 1754 1762 1750 1758 -1 
16 19830309 1746 1750 1735 1740 1 
17 19830310 1744 1745 1731 1735 0 
18 19830311 1735 1743 1732 1739 0 
19 19830314 1732 1734 1729 1730 1 
20 19830315 1735 1740 1733 1735 -1 
21 19830316 1737 1737 1733 1734 0 
22 19830317 1726 1729 1722 1723 1 
23 19830318 1722 1723 1718 1719 1 
24 19830321 1715 1715 1710 1711 1 
25 19830322 1715 1727 1715 1725 -1 
26 19830323 1723 1731 1723 1726 0 
27 19830324 1734 1736 1725 1726 0 
28 19830325 1722 1727 1720 1724 1 
29 19830328 1720 1721 1718 1720 0 
30 19830329 1718 1723 1717 1723 -1 

As you can see it's not working. Observation 13 should be -1, 17 & 18 should be 1 etc. 

Must be a very simple way to do this! 

	[[alternative HTML version deleted]]

