user113156
user113156

Reputation: 7137

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

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!

Upvotes: 1

Views: 2378

Answers (1)

MrFlick
MrFlick

Reputation: 206536

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))

Upvotes: 1

Related Questions