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?
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.
diff() function in R Language is used to find the difference between each consecutive pair of elements of a vector.
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.
diff wants a matrix or a vector rather than a data frame. Try
data.frame(diff(as.matrix(df)))
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.frame
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With