How to take the variation with respect to the number of days of the date difference in R

Asked

Viewed 95 times

1

I have a table in csv with 5 information, two with dates, two with prices, and one with the difference between dates.

  • I have date 1 fixed on a date and date 2 varying.

For example:

10/01/2018 > 11/01/2018
10/01/2018 > 12/01/2018 ...

  • I have the percentage of variation I picked up through the script below:

Tipo1_X <- (sd(Tipo1$precoin, na.rm = T)/mean(Tipo1$precoin, na.rm = T))*100 Tipo2_X <- (sd(Tipo2$precoin, na.rm = T)/mean(Tipo2$precoin, na.rm = T))*100 Tipo3_X <- (sd(Tipo3$precoin, na.rm = T)/mean(Tipo3$precoin, na.rm = T))*100 Tipo1_XX <- (sd(Tipo1$precoout, na.rm = T)/mean(Tipo1$precoout, na.rm = T))*100 Tipo2_XX <- (sd(Tipo2$precoout, na.rm = T)/mean(Tipo2$precoout, na.rm = T))*100 Tipo3_XX <- (sd(Tipo3$precoout, na.rm = T)/mean(Tipo3$precoout, na.rm = T))*100

  • Now, I need to know the variation of days in relation to that price. For example:

I have from day 10/01/2018 to day 11/01/2018, after day 10/01/2018 to day 12/01/2018.. From day 10 to day 11 is 1 day difference, from day 10 to day 12 are 2 days. I need to take the variation in the number of days of difference, but I’m not finding a way to do it in R. :(

PS: Illustrating how the result would be:

In differences of dates of 2 days the price varies by 10%, in 30 day date differences the price varies 5% and so on.

  • 1

    You can edit the question with the output of dput(Tipo1) or if the table is too large with the output of dput(head(Tipo1, 20)), please?

1 answer

0


I am not sure that the question is very clear and perhaps some additional information should be put. Either way, assuming you always want to calculate the difference from 10-01-2018, then what you need is to use indexes. You can calculate the results you are looking for as follows:

Diff_2_dias <- (valor_12012018/valor_100120118 -1) * 100
Diff_30_dias <- (valor_09022018/valor_100120118 -1) * 100

Note: variables are exemplifying, you have to choose values that are according to your dataframe and you can use R base without needing any package.

Since you’re manipulating serious temporals, I advise you to take a look at the package XTS documentation and convert the series into a time series. It will save you a lot of time in data manipulation.

https://rpubs.com/mohammadshadan/288218

https://www.datacamp.com/community/blog/r-xts-cheat-sheet

Browser other questions tagged

You are not signed in. Login or sign up in order to post.