Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R programming: How can I compute the difference between two cells in a data frame and save them in a new column

Trying to learn R and am stuck on an autocorrelation example. I want to regress the difference in x against the difference in y. I have x and y in a data frame, and would like the difference of x2 - x1 to be saved in a new column say dx. I have no idea how to go about this.

what I have:

data1

x   y
5   3
8   9
3   1
1   5
.   .
.   .
.   .

what I would like to get:

data1.dif

x   y   dx   dy
5   3   NA   NA
8   9    3    6
3   1   -5   -8
1   5   -2    4
.   .    .    .
.   .    .    .
like image 207
Travis Avatar asked Feb 23 '12 00:02

Travis


People also ask

How do you find differences between two columns in R?

We can compare two columns in R by using ifelse(). This statement is used to check the condition given and return the data accordingly.

How do I create a new variable from two existing variables in R?

Create new variables from existing variables in R?. To create new variables from existing variables, use the case when() function from the dplyr package in R.


1 Answers

Use diff with transform:

dat <- read.table(text="x   y
5   3
8   9
3   1
1   5", header=T)


transform(dat, dx=c(NA, diff(x)), dy=c(NA, diff(y)))

Yielding:

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

And as og dplyr:

library(dplyr)

dat %>%
    mutate(dx=c(NA, diff(x)), dy=c(NA, diff(y)))
like image 135
Tyler Rinker Avatar answered Sep 30 '22 04:09

Tyler Rinker