Lily
Lily

Reputation: 1

How can I compute the difference in consecutive rows for multiple columns?

I have a df consisting of daily returns for various maturities. The first column consists of dates and the next 12 are maturities. I want to create a new df that calculates the difference in consecutive daily rates. Not sure where to start.

enter image description here

Upvotes: 0

Views: 76

Answers (2)

Reid Williams
Reid Williams

Reputation: 381

In the future try to refrain just providing a picture and provide a reprex!

Here is one way to get what you're looking for:


df <- 
  data.frame(
    dates= c("2019-01-01", "2019-01-02", "2019-01-03"),
    original_numbers = c(1,2,3)
  )

df2 <- df %>% 
  mutate(
    difference = original_numbers - lag(original_numbers)
    )

Upvotes: 2

akrun
akrun

Reputation: 886948

With multiple columns, diff can applied

rbind(0, diff(as.matrix(df[-1])))

Or we can use dplyr

library(dplyr)
df %>%
   mutate_at(vars(-Date), ~ . - lag(.))

Reproducible example

diff(as.matrix(head(mtcars)))

Upvotes: 2

Related Questions