5.5 Reduce
Sometimes, we want to get a final result by applying operation one by one.
5.5.1 On vector
For example, 2-day moving average is \(EMA_{t}=\frac{1}{3}p_{t}+\frac{2}{3}EMA_{t-1}\).
The following example shows the 2-day EMA with initial EMA being 5.
price <- 1:10
initial <- 5
for (i in 1:length(z)) {
x <- (x + 2*z[i])/3
}
x
## [1] 6.548036 6.548443 6.549256
The following example use Reduce to simplify the code.
price <- 1:10
initial <- 5
x <- Reduce(function(x,y){(x+2*y)/3},price,initial)
x
## [1] 9.500093
5.5.2 On list
The following example shows how we can combine data sets.
HI <- data.frame(stock=c(1,2), high=c(7,8))
LO <- data.frame(stock=c(1,2), low=c(1,2))
OP <- data.frame(stock=c(1,2), open=c(3,6))
CL <- data.frame(stock=c(1,2), close=c(5,5))
df <-merge(HI,LO)
df <-merge(df,OP)
df <-merge(df,CL)
df
## stock high low open close
## 1 1 7 1 3 5
## 2 2 8 2 6 5
Since merging is one by one on the data.frame, we just need to create a list of data.frame.
HI <- data.frame(stock=c(1,2), high=c(7,8))
LO <- data.frame(stock=c(1,2), low=c(1,2))
OP <- data.frame(stock=c(1,2), open=c(3,6))
CL <- data.frame(stock=c(1,2), close=c(5,5))
df <- Reduce(function(x,y) {merge(x,y)}, list(HI, LO, OP, CL))
df
## stock high low open close
## 1 1 7 1 3 5
## 2 2 8 2 6 5