'Aplicate a complex operation on a column to create a new dataframe in R
I have a dataframe that looks like the the following, lets call it DF
| Symbol | Date | volume | price |
|---|---|---|---|
| A | 2014-01-01 | 1 | 5 |
| A | 2014-01-02 | 3 | 8 |
| A | 2014-01-03 | 7 | 4 |
| A | 2014-01-07 | 3 | 6 |
| A | 2014-01-08 | 34 | 7 |
| A | 2014-01-09 | 45 | 34 |
| A | 2014-01-10 | 4 | 5 |
| A | 2014-01-11 | 9 | 7 |
| A | 2014-01-14 | 8 | 6 |
| A | 2014-01-15 | 4 | 4 |
| A | 2014-01-16 | 0 | 7 |
| A | 2014-01-17 | 4 | 7 |
I want to apply the next operation to the price column:
diff(log(DF$price))
And generate a datafra like this:
| Date | returns |
|---|---|
| 2014-01-01 | 4 |
| 2014-01-02 | 6 |
| 2014-01-03 | 8 |
| 2014-01-07 | 2 |
| 2014-01-08 | 14 |
| 2014-01-09 | 5 |
| 2014-01-10 | 1 |
| 2014-01-11 | 2 |
| 2014-01-14 | 8 |
| 2014-01-15 | 4 |
| 2014-01-16 | 0 |
| 2014-01-17 | 4 |
(The numbers, in the column returns i the examples not are the desired one, are just random numbers that i put to ilustrate, i need that in each row of that column appears the correspondent result of diff(log(DF$price)))
I tried the next lines of code but it did not result:
Ret <- DF %>% group_by(date) %>%
mutate(Ret_i = diff(log(DF$price)))%>%
summarise(Ret_i)
Thanks for reading and I would apreciate any help
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
