Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting each column from its previous one in a data frame

Tags:

r

dplyr

purrr

I have a very simple case here in which I would like to subtract each column from its previous one. As a matter of fact I am looking for a sliding subtraction as the first column stays as is and then the first one subtracts the second one and second one subtracts the third one and so on till the last column. here is my sample data set:

structure(list(x = c(1, 0, 0, 0), y = c(1, 0, 1, 1), z = c(0, 
1, 1, 1)), class = "data.frame", row.names = c(NA, -4L))

and my desired output:

structure(list(x = c(1, 0, 0, 0), y = c(0, 0, 1, 1), z = c(-1, 
1, 0, 0)), class = "data.frame", row.names = c(NA, -4L))

I am personally looking for a solution with purrr family of functions. I also thought about slider but I'm not quite familiar with the latter one. So I would appreciate any help and idea with these two packages in advance. Thank you very much.

like image 704
Anoushiravan R Avatar asked Dec 05 '25 05:12

Anoushiravan R


1 Answers

A simple dplyr only solution-

  • cur_data() inside mutate/summarise just creates a whole copy. So
  • just substract cur_data()[-ncol(.)] from cur_data()[-1]
  • with pmap_df you can do similar things
df <- structure(list(x = c(1, 0, 0, 0), y = c(1, 0, 1, 1), z = c(0, 
                                                           1, 1, 1)), class = "data.frame", row.names = c(NA, -4L))


library(dplyr)

df %>% 
  mutate(cur_data()[-1] - cur_data()[-ncol(.)])
#>   x y  z
#> 1 1 0 -1
#> 2 0 0  1
#> 3 0 1  0
#> 4 0 1  0

similarly

pmap_dfr(df, ~c(c(...)[1], c(...)[-1] - c(...)[-ncol(df)]))
like image 66
AnilGoyal Avatar answered Dec 07 '25 19:12

AnilGoyal