简体   繁体   中英

How to apply a function and assign multiple variables to a grouped tibble

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM