简体   繁体   English

如何应用 function 并将多个变量分配给分组的 tibble

[英]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.我想在不离开管道的情况下将 function 应用于分组的 tibble。 Here's an example:这是一个例子:

dataframe dataframe

test = data.frame(ticker=c(rep(c('A','B','C'),100)),price=rnorm(300))

function 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.最终结果将是一个带有代码、价格、MACD、信号和变化的 dataframe。

I would give the do() function a go, something along these lines:我会给do() function 一个 go,类似以下内容:

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来自dplyrdo()文档: https://dplyr.tidyverse.org/reference/do.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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