簡體   English   中英

如何應用 function 並將多個變量分配給分組的 tibble

[英]How to apply a function and assign multiple variables to a grouped tibble

我想在不離開管道的情況下將 function 應用於分組的 tibble。 這是一個例子:

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)

像這樣的東西(但有效):

 prices %>%
  group_by(ticker) %>%
  group_modify(~ {
    .x %>% MACD(.$price.close, nFast=12*30, nSlow=26*30,nSig=9, percent=FALSE)
  }) %>%
mutate(change=macd-signal)

最終結果將是一個帶有代碼、價格、MACD、信號和變化的 dataframe。

我會給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)

來自dplyrdo()文檔: https://dplyr.tidyverse.org/reference/do.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM