I am trying to use mutate to create a new column in my data frame, with the output of a function.
Here is my code
StockData <- StockData %>%
mutate(yrReturn=sapply(StockReturns[row_number()+1], yearReturn))
and here is the function
yearReturn <- function(DailyReturns){
ans = 1.0;
for (day in 1:nrow(DailyReturns)){
ans = ans + ans * as.numeric(DailyReturns[day,1]);
}
print (ans)
return (ans - 1.0)
}
it seems like something is not going right with sapply, and this throws an error.
But this works:
StockData <- StockData %>%
mutate(volatility = sapply(StockReturns[row_number()+1], sd))
expecting to add a new column to StockData with yrReturn
Michael Zimet is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
5
Though we need the information requested in the comments, I can provide an answer for what I think you’re doing. Based on the variable names and code provided, you want a column of cumulative stock value and returns.
First, I’ll generate data that I assume is similar to what you have.
library(dplyr)
library(tibble)
set.seed(234)
StockData <- tibble(
DailyReturns = rnorm(10, 0, .25)
)
head(StockData, 3)
# A tibble: 3 × 1
DailyReturns
<dbl>
1 0.165
2 -0.513
3 -0.375
As I mentioned in my comment, you generally want to avoid assigning columns row by row using a for loop. Base R has cumulative functions including cumprod
.
StockData <-
StockData %>%
mutate(
cumul_value = cumprod(1 + DailyReturns), # replaces ans = ans + ans * as.numeric(DailyReturns[day,1]);
cumul_return = cumul_value - 1
)
StockData
# A tibble: 10 × 3
DailyReturns cumul_value cumul_return
<dbl> <dbl> <dbl>
1 0.165 1.17 0.165
2 -0.513 0.567 -0.433
3 -0.375 0.355 -0.645
4 0.368 0.485 -0.515
5 0.365 0.662 -0.338
6 0.0350 0.685 -0.315
7 0.0523 0.721 -0.279
8 -0.759 0.174 -0.826
9 -0.122 0.153 -0.847
10 -0.272 0.111 -0.889
It seems to work as sd takes a vector as an argument, while dailyReturns seems to take a data.frame (you’re using nrow on it). Maybe using length in dailyReturns, if you’re expecting a vector?
Guillaume is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.