Amit
Amit

Reputation: 9

How To Use Diff Row-wise

I have a column with values c(80,70,50,40, 30). I need to subtract(80-70) and so on as show below.

Below is the column and desired output. First value required is 0 and then after diff value. I'm trying this in R.

Col 1   Diff
80      0
70     10
50     20
40     10
30     10

Upvotes: 0

Views: 136

Answers (2)

Bathsheba
Bathsheba

Reputation: 234715

You want diff:

c(0, -diff(c(80, 70, 50, 40, 30)))

Upvotes: 3

pyll
pyll

Reputation: 1764

x <- c(80,70,50,40,30)
y <- c(100, 120, 30, 20, 10)

df <- data.frame(x, y)

df$x1 <- c(0, abs(diff(x)))
df$y1 <- c(0, abs(diff(y)))

However, the above only works when the values are in descending order...so use this one instead.

df$x2 <- c(0, 0-(diff(x))) 
df$y2 <- c(0, 0-(diff(y)))

Upvotes: 0

Related Questions