Applying a function within `mutate()` from `dplyr`

2019-09-03 03:30发布

问题:

I am trying to apply a custom function within the dplyr package.

Data & function

library(tidyquant)
library(dplyr)

Ra <- c("AMZN","FB","GOOG", "NFLX") %>%
  tq_get(get = "stock.prices",
         from = "2013-01-01",
         to = "2016-12-31")


Rb <- "SPY" %>%
  tq_get(get = "stock.prices",
         from = "2013-01-01",
         to = "2016-12-31")

stock_returns_daily <- Ra
benchmark_returns_daily <- Rb  

RaRb <- left_join(stock_returns_daily, benchmark_returns_daily, by = c("date" = "date"))
normalise_series <- function(xdat) xdat / coredata(xdat)[1]

(Note: This is a follow up question regarding a previous post I made here which is not directly related to this question).

I am trying to apply the normalise_series <- function(xdat) xdat / coredata(xdat)[1] part of the above code to a dplyr piece. What I have so far is;

x <- RaRb %>% 
  group_by(symbol) %>%
  select(symbol, adjusted.x) %>%
  rowwise() %>% 
  mutate(adj.x = normalise_series(adjusted.x))

And I am not completely sure why this is not working. I know I am missing something but do not know what/why. The column I create, just creates a vector one 1`s

I am trying to apply the function (a normalisation function on stock prices) to each group in the dataframe and not the whole column. (whereas, as pointed out by @Noah I was applying the normalisation function across all stocks.

Any pointers in the right direction would be great!

回答1:

The rowwise() verb makes it so each command is performed separately on each row. This is not what you want because you want to normalize over all the values in the group. Not one row. Just take that part out.

x <- RaRb %>% 
  group_by(symbol) %>%
  select(symbol, adjusted.x) %>%
  mutate(adj.x = normalise_series(adjusted.x))


标签: r dplyr