R: how can I calculate the difference between two cells in a data frame and save them in a new column

An attempt to find out R and get stuck with autocorrelation as an example. I want to regress the difference in x from the difference in y. I have x and y in the data frame and would like the difference x2-x1 to be stored in a new column, for example, dx. I have no idea how to do this.

what i have:

data1

xy 5 3 8 9 3 1 1 5 . . . . . . 

what i would like to get:

 data1.dif xy dx dy 5 3 NA NA 8 9 3 6 3 1 -5 -8 1 5 -2 4 . . . . . . . . 
+5
source share
2 answers

Use diff and bind NA to the beginning of the resulting vectors.

eg.

 data1 <- read.table(text=' xy 1 5 3 2 8 9 3 3 1 4 1 5') # diff calculates the difference between consecutive pairs of # vector elements diff(data1$x) [1] 3 -5 -2 # apply diff to each column of data1, bind an NA row to the beginning, # and bind the resulting columns to the original df data1.dif <- cbind(data1, rbind(NA, apply(data1, 2, diff))) names(data1.dif) <- c('x', 'y', 'dx', 'dy') data1.dif xy dx dy 1 5 3 NA NA 2 8 9 3 6 3 3 1 -5 -8 4 1 5 -2 4 
+5
source

Use diff with transform :

 dat <- read.table(text="xy 5 3 8 9 3 1 1 5", header=T) transform(dat, dx=c(NA, diff(x)), dy=c(NA, diff(y))) 

Yielding:

  xy dx dy 1 5 3 NA NA 2 8 9 3 6 3 3 1 -5 -8 4 1 5 -2 4 

And like og dplyr :

 library(dplyr) dat %>% mutate(dx=c(NA, diff(x)), dy=c(NA, diff(y))) 
+8
source

Source: https://habr.com/ru/post/909227/


All Articles