Skip to Content
R Programming By Example
book

R Programming By Example

by Omar Trejo Navarro
December 2017
Beginner to intermediate
470 pages
12h 29m
English
Packt Publishing
Content preview from R Programming By Example

Removing unnecessary logic

There are times when simple logic shows us that there are parts of our implementations that are unnecessary. In this particular case, the accumulation of period_prices can be avoided by setting sma to 0 initially instead of NA, and adding to it each price. However, when doing so, we lose track of the number of elements in the vector, so the mean() function doesn't make sense any more, and we proceed to simply divide the sum by period as we were doing earlier:

sma_slow_5 <- function(period, symbol, data) {    result <- NULL    for(end in 1:nrow(data)) {        position <- end        sma <- 0        n_accumulated <- 0        if (data[end, "symbol"] == symbol) {            while(n_accumulated < period & position >= 1) {                if (data[position, "symbol"] == symbol) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Efficient R Programming

Efficient R Programming

Colin Gillespie, Robin Lovelace
R Programming

R Programming

Jared P. Lander

Publisher Resources

ISBN: 9781788292542Supplemental Content