-1

I have a data table with 117 objects (rows) and 51 variables (columns). I would like to subtract each row from the previous one and post the results in a new data table.

My data table are a time series of interest rates and I want to calculate the daily difference.

2 Answers2

1
apply(dt, MARGIN = 2, diff)

would calculate, for each column, the difference between each element and the previous one. Try:

a = data.frame(matrix(c(1,1,1,3,3,3,7,7,7),byrow = T,nrow=3))
apply(a,2,diff)
Johann
  • 298
  • 2
  • 11
0

Let's say you have this as example data:

df <- data.frame(date = as.Date(c("2019-01-03", "2019-01-04", "2019-01-05", "2019-01-06")), value = c(3,5,7,6))

        date value
1 2019-01-03     3
2 2019-01-04     5
3 2019-01-05     7
4 2019-01-06     6

Then using dplyr from tidyverse you can do this:

library(tidyverse)
df2 <- df %>% 
  mutate(difference = lag(value, n=1L) - value)

        date value difference
1 2019-01-03     3         NA
2 2019-01-04     5         -2
3 2019-01-05     7         -2
4 2019-01-06     6          1

... you'll just need to decide what to do with that first NA in row index 1.

nycrefugee
  • 1,629
  • 1
  • 10
  • 23