Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R how can I calculate difference between rows in a data frame

Tags:

dataframe

r

diff

Here is a simple example of my problem:

> df <- data.frame(ID=1:10,Score=4*10:1) > df        ID Score     1   1    40     2   2    36     3   3    32     4   4    28     5   5    24     6   6    20     7   7    16     8   8    12     9   9     8     10 10     4     > diff(df)  Error in r[i1] - r[-length(r):-(length(r) - lag + 1L)] :    non-numeric argument to binary operator 

Can anyone tell me why this error occurs?

like image 672
ManInMoon Avatar asked Apr 25 '13 10:04

ManInMoon


People also ask

How do you find the difference between two rows in a data frame?

Difference between rows or columns of a pandas DataFrame object is found using the diff() method. The axis parameter decides whether difference to be calculated is between rows or between columns. When the periods parameter assumes positive values, difference is found by subtracting the previous row from the next row.

How do you show difference in R?

diff() function in R Language is used to find the difference between each consecutive pair of elements of a vector.

How do you subtract data in R?

Data Visualization using R Programming To do this, we simply need to use minus sign. For example, if we have data-frames df1 and df2 then the subtraction can be found as df1-df2.


2 Answers

diff wants a matrix or a vector rather than a data frame. Try

data.frame(diff(as.matrix(df))) 
like image 109
aPaulT Avatar answered Sep 20 '22 14:09

aPaulT


Perhaps you are looking for something like this:

> tail(df, -1) - head(df, -1)    ID Score 2   1    -4 3   1    -4 4   1    -4 5   1    -4 6   1    -4 7   1    -4 8   1    -4 9   1    -4 10  1    -4 

You can subtract or add two data.frames together if they are the same dimensions. So, what we are doing here is subtracting one data.frame that is missing the first row (tail(df, -1)) and one that is missing the last row (head(df, -1)) and subtracting them.

like image 28
A5C1D2H2I1M1N2O1R2T1 Avatar answered Sep 22 '22 14:09

A5C1D2H2I1M1N2O1R2T1