Reputation: 769
I'd like to apply a function to a grouped tibble without leaving my pipes. Here's an example:
dataframe
test = data.frame(ticker=c(rep(c('A','B','C'),100)),price=rnorm(300))
function
MACD(test$price, nFast=12*30, nSlow=26*30,nSig=9, percent=FALSE)
Something like this (but working):
prices %>%
group_by(ticker) %>%
group_modify(~ {
.x %>% MACD(.$price.close, nFast=12*30, nSlow=26*30,nSig=9, percent=FALSE)
}) %>%
mutate(change=macd-signal)
The end result would be a single dataframe with ticker, price, macd, signal and change.
Upvotes: 1
Views: 72
Reputation: 1173
I would give the do()
function a go, something along these lines:
prices %>%
group_by(ticker) %>%
do(macd = MACD(.$price.close, nFast=12*30, nSlow=26*30,nSig=9, percent=FALSE)) %>%
mutate(change=macd-signal)
Documentation for do()
from dplyr
: https://dplyr.tidyverse.org/reference/do.html
Upvotes: 1