I am attempting to manipulate some data to create a spaghetti plot with something like this:
testData =
tribble(~date, ~close,
1, 1,
2, 2,
3, 3,
4, 4,
5, 5,
6, 6,
7, 7,
8, 8
)
historySize = 30
testData2 =
testData %>%
arrange(desc(date)) %>%
mutate(
futureCloseList = accumulate(
.x = row_number()[-1], # apply the function on all rows, except the first one.
.init = close[1], # initial value for the first row.
.f = function(last_result, i) {
c(close[i], head(last_result, historySize))
}
),
futureCloseList = futureCloseList / close # <<<--- problem here
) %>%
arrange(date)
td3 =
testData2 %>%
unnest(cols = c(futureCloseList) ) %>%
rename( futureClose = futureCloseList ) %>%
group_by(date) %>%
mutate( days = seq( from=0, to=n()-1, by=1),
)
ggplot( data = td3,
aes( x = days, y = futureClose, group = date)
) +
geom_line()
> dput(testData2)
structure(list(date = c(1, 2, 3, 4, 5, 6, 7, 8), close = c(1,
2, 3, 4, 5, 6, 7, 8), futureCloseList = list(c(1, 2, 3, 4, 5,
6, 7, 8), c(2, 3, 4, 5, 6, 7, 8), c(3, 4, 5, 6, 7, 8), c(4, 5,
6, 7, 8), c(5, 6, 7, 8), c(6, 7, 8), c(7, 8), 8)), row.names = c(NA,
-8L), class = c("tbl_df", "tbl", "data. Frame"))
The idea to take a history of dated values ("close") and build a limited history list ("futureCloseList") in the tibble. This works fine. But I then wish to scale the list by the first value ("futureCloseList / close "), but I'm having trouble converting the list into a format that works. I've tried various calls to map and lapply, but seem unable to get them to work for me.
Any suggestions of what to do would be much appreciated.