Find difference between each column and the previous one in R

Viewed 22

I have:


id   time.1     time.2     time.3       
1      2          3         4.5         
2      4          6         7            
3      2         2.1       2.8           


And I would like subtract each column from the next one, to get:




id   time.1    diff.2.1   time.2    diff.3.2     time.3       
1      2          1         3           1.5        4.5          
2      4          2         6            1          7            
3      2         .1        2.1          .7         2.8             



1 Answers
nm1 <- sub("time", "diff", names(df1)[-1])
nm2 <- paste0(nm1[-1], sub("diff", "", nm1[-length(nm1)]))
df1[nm2] <- df1[3:4] - df1[2:3]

library(dplyr)
library(stringr)
df1 %>% 
  mutate(across(c(time.2:time.3), 
   .names = "{str_replace(.col, 'time', 'diff')}") -
    across(c(time.1:time.2))) %>% 
  select(id, order(readr::parse_number(names(.)[-1]), 
   str_detect(names(.)[-1], "time")) + 1) %>%
  rename_with(~ str_c(.x, ".", seq_along(.x)), starts_with("diff"))

-output

  id time.1 diff.2.1 time.2 diff.3.2 time.3
1  1      2      1.0    3.0      1.5    4.5
2  2      4      2.0    6.0      1.0    7.0
3  3      2      0.1    2.1      0.7    2.8

data

df1 <- structure(list(id = 1:3, time.1 = c(2L, 4L, 2L), time.2 = c(3, 
6, 2.1), time.3 = c(4.5, 7, 2.8)), class = "data.frame", row.names = c(NA, 
-3L))
Related